I've got:
class ArticleController(SubbaseController):
def view(self):
c.referral = self.detect_referral.referrer
return render('/article.mako')
#staticmethod
def detect_referral():
referrer = request.META.get('HTTP_REFERRER', '')
I'm trying to reference the referrer inside of the view action from the detect_referral static method, but I keep getting: 'function' object has no attribute 'referrer' instead. Any ideas?
Also, is that the correct way to get the referrer?
You aren't returning the referrer from detect_referral, and detect_referral is not a property, so you cannot use that syntax.
class ArticleController(BaseController):
def view(self):
c.referral = self.detect_referral()
return render('/article.mako')
#staticmethod
def detect_referral():
return request.META.get('HTTP_REFERRER', '')
It's a local variable inside detect_referral(), and as such its lifetime is limited to the execution time of the method. Before the method is called and after the method returns local variables simply don't exist. (You don't even seem to call the method, so the local variable exists at no time of the execution of your program.)
Most probably you don't want a static method here. (You almost never want a static method in Python. I cannot remember that I ever used one.) Maybe all you need is a class attribute:
class ArticleController(SubbaseController):
referrer = request.META.get('HTTP_REFERRER', '')
def view(self):
c.referral = self.referrer
return render('/article.mako')
Note that the class body is executed once at class definition time.
Related
I want to restrict a parameter within a set of options. If the function is called a parameter must be restricted to a couple of options.
This is what I have until now
class GetFileMethod:
URL = 'url'
ATTACHMENT = 'attachment'
class MailClient
def GetFile(self,method)
MailClient.GetFile(GetFileMethod.URL) #works ok, but
MailClient.GetFile("lalala") #should raise an error
Any suggestions?
def GetFile(self, method):
if method not in {'url','attachment'}:
raise ValueError
I would make GetFileMethod a method of the MailClient class and it will make life easier controlling the input.
Change your class MainClient to this:-
you need to check the value of method that you are providing in the namespace of the class GetFileMethod so that :-
GetFileMethod.__dict__.values()
class MailClient:
def GetFile(self, method):
if method in GetFileMethod.__dict__.values():
return 'Yes'
else:
return 'No'
I'm writing tests for a Django application and using a attribute on my test class to store which view it's supposed to be testing, like this:
# IN TESTS.PY
class OrderTests(TestCase, ShopTest):
_VIEW = views.order
def test_gateway_answer(self):
url = 'whatever url'
request = self.request_factory(url, 'GET')
self._VIEW(request, **{'sku': order.sku})
# IN VIEWS.PY
def order(request, sku)
...
My guess is that the problem I'm having is caused because since I'm calling an attribute of the OrderTests class, python assumes I wanna send self and then order get the wrong arguments. Easy to solve... just not use it as a class attribute, but I was wondering if there's a way to tell python to not send self in this case.
Thanks.
This happens because in Python functions are descriptors, so when they are accessed on class instances they bind their first (assumed self) parameter to the instance.
You could access _VIEW on the class, not on the instance:
class OrderTests(TestCase, ShopTest):
_VIEW = views.order
def test_gateway_answer(self):
url = 'whatever url'
request = self.request_factory(url, 'GET')
OrderTests._VIEW(request, **{'sku': order.sku})
Alternatively, you can wrap it in staticmethod to prevent it being bound to the instance:
class OrderTests(TestCase, ShopTest):
_VIEW = staticmethod(views.order)
def test_gateway_answer(self):
url = 'whatever url'
request = self.request_factory(url, 'GET')
self._VIEW(request, **{'sku': order.sku})
I'm doing a database insert script in pycassa. I want to set up a public static class that defines some variables that will get used a lot by other functions later on. Heres what I have...
class ks_refs():
pool = ConnectionPool('TweetsKS')
user_name_cf = self.cf_connect('UserName')
user_tweet_cf = self.cf_connect('UserTweet')
def cf_connect(column_family):
cf = pycassa.ColumnFamily(self.pool, column_family)
return cf
I haven't even tried to run this yet because I'm sure it wont work. You can see I want this static variable 'pool' first, and then set up user_name_cf and user_tweet_cf (and some more later) using the cf_connect method which needs 'pool' to work.
I know I could put that method outside the class, or I could have this non-static and make an instance of it, but I want to try this because this is what I really want (before I was just using globals but I think a static class holding all this is the best idea)
I think you want to have a class method instead:
#classmethod
def cf_connect(cls, column_family):
cf = pycassa.ColumnFamily(cls.pool, column_family)
return cf
Now you can refer to the pool defined on your class with ease.
Your user_name_cf and user_tweet_cf 'attributes' will not work, however. You can add these after having created the class definition:
class ks_refs():
pool = ConnectionPool('TweetsKS')
#classmethod
def cf_connect(cls, column_family):
cf = pycassa.ColumnFamily(cls.pool, column_family)
return cf
user_name_cf = ks_refs.cf_connect('UserName')
user_tweet_cf = ks_refs.cf_connect('UserTweet')
where they are then module-level constants, or you can add them to the class as attributes after the fact:
ks_refs.user_name_cf = ks_refs.cf_connect('UserName')
ks_refs.user_tweet_cf = ks_refs.cf_connect('UserTweet')
I'm new to python and GAE and I thought python will act as any other OO language, but apparently not. How does __init__(self): function gives me different results in the following code?
class BaseHandler(webapp.RequestHandler):
#property
def current_user(self):
if not hasattr(self, "_current_user"):
self._current_user = None
cookie = facebook.get_user_from_cookie(self.request.cookies, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
user = User.get_by_key_name(cookie["uid"])
return self._current_user
class SubmitHandler(BaseHandler):
template_values = dict(facebook_app_id=FACEBOOK_APP_ID)
def __init__(self):
#throws error : AttributeError: 'SubmitHandler' object has no attribute 'request'
self.template_values['current_user'] = self.current_user
def get(self):
#this one function is error free
self.template_values['current_user'] = self.current_user
How do I access the class' parent property?
If you look at your SubmitHandler class you'll notice that it indeed does not have a request attribute -- at least, none you set, and none you give the parent class a chance to set. Perhaps what you need to do is call the parentclass __init__ method before you try to access self.current_user.
As a side note, you should realize that the template_values dict you define inside the SubmitHandler class there is a class attribute, and thus shared between all instances of the class. Since you assign it something instance-specific in your __init__, you probably mean for it to be an instance attribute instead. Assign it to self.template_values in your __init__ method.
There's nothing particularly different about Python's object inheritance.
By defining __init__, you have told Python that this is all that needs to be done to initialize the object. You're therefore denying it the chance to run the superclass's initialization code. You need to call super:
def __init__(self, *args, **kwargs):
super(SubmitHandler, self).__init__(*args, **kwargs)
self.template_values['current_user'] = self.current_user
This might however not solve your problem - you're failing to take into account the possibility that self.request is initialized at another point in the program, which is why it works by the time get is called.
self.request and self.response are not set by the class constructor in webapp. They're set later, when the framework calls the handler's initialize method. You can override this, just make sure you call the parent class's initialize before doing anything else.
For my exception class I'd like to find out whether the function which instantiated the exception object is a method and if so, show the class name.
So in the init method of my exception class I get the name of the calling function:
frame, module, line, function, context, index = inspect.stack()[1]
But is there any way the get the class name (if any) of the calling function?
Assuming the frame is for an instance method:
self_argument = frame.f_code.co_varnames[0] # This *should* be 'self'.
instance = frame.f_locals[self_argument]
class_name = instance.__class__.__name__