简体   繁体   中英

files getting wrongly cached by the web server while using standard python file operations (Django)

I have a Django app, which populates content from a text file, and populates them using the initial option in a standard form. The file gets updated on the server, but when the form gets refreshed, it picks up content from the a previously saved version, or the version before the Apache WebServer was reloaded.

This means that the file is getting cached, and the content is picked up from a wrong cache and not the new file.

Here is my code. How do I ensure that everytime, spamsource function picks up the content from the most recently saved file, instead of from a cache.

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

The issue is simply that all the parameters to fields are evaluated at form definition time. So, the initial value for domains is set to whatever the return value is from spamsource() at the time the form is defined, ie usually when the server is started.

One way of fixing this would be to override the form's __init__ method and set the initial value for domains there:

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

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

Alternatively, you could set the initial value when you instantiate the form in your view:

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

I fixed this. The problem was the presence of all the caching middleware in settings.py, which were being used to speed up another side of the web app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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