【问题标题】:files getting wrongly cached by the web server while using standard python file operations (Django)使用标准 python 文件操作 (Django) 时,文件被 Web 服务器错误缓存
【发布时间】:2011-03-26 18:12:20
【问题描述】:

我有一个 Django 应用程序,它从文本文件中填充内容,并使用标准形式的初始选项填充它们。文件在服务器上更新,但当表单刷新时,它会从以前保存的版本或重新加载 Apache WebServer 之前的版本中获取内容。

这意味着文件正在被缓存,内容是从错误的缓存而不是新文件中提取的。

这是我的代码。如何确保每次 spamsource 函数都从最近保存的文件中获取内容,而不是从缓存中获取内容。

def spamsource():
   try:
    f= open('center_access', 'r')
    read=f.read()
    # some manipulation on read 
    f.close()
    return read
   except IOError:
    return "prono.nr"

class SpamForm(forms.Form):

    domains =forms.CharField(widget=forms.Textarea(attrs=attrs_dict),
                                label=_(u'Domains to be Banned'), initial= spamsource())
def function(request):
    # It writes the file center_access based on the changes in the textbox domains

【问题讨论】:

  • Apache 缓存是如何出现的? Python 访问文件系统。而python是通过apache调用的。

标签: python django file caching


【解决方案1】:

问题只是字段的所有参数都是在表单定义时评估的。因此,domains 的初始值设置为在定义表单时(即通常在服务器启动时)来自 spamsource() 的返回值。

解决此问题的一种方法是覆盖表单的 __init__ 方法并在那里设置域的初始值:

class SpamForm(forms.Form):
    domains = ...

    def __init__(self, *args, **kwargs):
        super(SpamForm, self).__init__(*args, **kwargs)
        self.fields['domains'].initial = spamsource()

或者,您可以在视图中实例化表单时设置初始值:

form = SpamForm(initial={'domains': spamsource()})

【讨论】:

  • 没有。这不起作用。我仍然需要重新启动 Apache Web 服务器才能获得结果。必须有办法删除文件缓存并再次加载它
  • 哪个不行?在 Django 中没有缓存文件操作这样的东西,所以有些事情你没有告诉我们。
  • +1 从方法中获取值的函数定义是不可调试的错误。每个人都会被咬一次!
【解决方案2】:

我解决了这个问题。问题在于 settings.py 中存在所有缓存中间件,这些中间件被用来加速 Web 应用程序的另一端。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    • 2011-12-13
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 2015-07-06
    • 1970-01-01
    相关资源
    最近更新 更多