Referencing variable from static method inside another action in Pylons
Question
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?
Solution
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', '')
OTHER TIPS
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.