【问题标题】:django module-level cachedjango 模块级缓存
【发布时间】:2011-11-22 19:19:13
【问题描述】:

我正在尝试将值存储在模块级变量中以供以后检索。 使用 GET 方法调用此函数时会抛出此错误:local variable 'ICS_CACHE' referenced before assignment

我在这里做错了什么?

ICS_CACHE = None
def ical_feed(request):
    if request.method == "POST":
        response = HttpResponse(request.POST['file_contents'], content_type='text/calendar')
        response['Content-Disposition'] = 'attachment; filename=%s' % request.POST['file_name']
        ICS_CACHE = response
        return response
    elif request.method == "GET":
        return ICS_CACHE

    raise Http404

我构建了一个基本示例,看看一个函数是否可以读取模块常量并且它工作得很好:

x = 5

def f():
    print x

f()

---> "5"

【问题讨论】:

    标签: python django caching variables scope


    【解决方案1】:

    添加

    global ISC_CACHE
    

    作为函数的第一行。您在函数体内对其进行赋值,因此 python 假定它是一个局部变量。但是,作为一个局部变量,如果不先赋值就不能返回它。

    global 语句让解析器知道变量来自函数范围之外,以便您可以返回它的值。

    针对您发布的第二个示例,您所展示的内容显示了当您不尝试分配全局变量时解析器如何处理它们。

    这可能会更清楚:

    x = 5 # global scope
    def f():
        print x # This must be global, since it is never assigned in this function
    
    >>> f()
    5
    
    def g():
        x = 6 # This is a local variable, since we're assigning to it here
        print x
    
    >>> g()
    6
    
    def h():
        print x # Python will parse this as a local variable, since it is assigned to below
        x = 7
    
    >>> h()
    UnboundLocalError: local variable 'x' referenced before assignment
    
    
    def i():
        global x # Now we're making this a global variable, explicitly
        print x
        x = 8 # This is the global x, too
    
    >>> x # Print the global x
    5
    >>> i()
    5
    >>> x # What is the global x now?
    8
    

    【讨论】:

    • 出于某种原因,这似乎不是很pythonic...我想知道包含 global 关键字的基本原理是什么。
    猜你喜欢
    • 2011-11-28
    • 2015-05-25
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 2017-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多