简体   繁体   English

在Pylons中的另一个动作中引用静态方法中的变量

[英]Referencing variable from static method inside another action in Pylons

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. 我正在尝试从detect_referral静态方法引用view动作内的引荐来源,但我不断得到:'function'对象没有属性'referrer'。 Any ideas? 有任何想法吗?

Also, is that the correct way to get the referrer? 另外,这是获取引荐来源网址的正确方法吗?

It's a local variable inside detect_referral() , and as such its lifetime is limited to the execution time of the method. 它是detect_referral()内的局部变量,因此其生存期受限于方法的执行时间。 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: (您几乎从不需要Python中的静态方法。我不记得我曾经使用过一种方法。)也许您只需要一个class属性:

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. 注意,类主体在类定义时执行一次。

You aren't returning the referrer from detect_referral , and detect_referral is not a property, so you cannot use that syntax. 您不是从detect_referral返回referrer detect_referral ,而且detect_referral不是属性,因此不能使用该语法。

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', '')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM