How to I reload global vars on every page refresh in DJango

Here is my problem. DJango continues to store all the global objects after the first run of a script. For instance, an object you instantiate in views.py globally will be there until you restart the app server. This is fine unless your object is tied to some outside resource that may time out. Now the way I was thinking to correct was some sort of factory method that checks if the object is instantiated and creates it if it's not, and then returns it. However, the this fails because the object exists there since the last page request, so a factory method is always returning the object that was instantiated during the first request.

What I am looking for is a way to trigger something to happen on a per request basis. I have seen ways of doing this by implementing your own middleware, but I think that is overkill. Does anyone know of some reserved methods or some other per request trigger.


Asked by: Briony517 | Posted: 06-12-2021






Answer 1

Simple: Don't use global objects. If you want an object inside the view, instantiate it inside the view, not as global. That way it will be collected after the view ends.

Answered by: Brad561 | Posted: 07-01-2022



Similar questions

python - Query refresh issue after using MySQL to load file

I use SqlAlchemy as my ORM. I do a mysqlimport cmd through subprocess. Then before and after the execution, I query the db records with the statistics_db method. But the records count results after import from CSV didn't increase. I think this is an SqlAlchemy problem. def statistics_db(f): @wraps(f) def wrapper(*args,**args2): q=Product.query.filter(&qu...


python - Using a file watch to refresh a log viewer using PyQt4

I've implemented a very simple log viewer in Python using PyQt4. I am interested in using it to follow the execution of a program, so the list view has to be refreshed when a new line is appended to the log file. Here is my implementation (without the watch): import sys from PyQt4.QtCore import * from PyQt4.QtGui import * class LogEntryModel(QAbstractListModel): def __init__(self, logfi...


python - How do I refresh the values on an object in Django?

I have a model object in Django. One of the methods on the object uses row-level locking to ensure values are accurate, like so: class Foo(model.Model): counter = models.IntegerField() @transaction.commit_on_success def increment(self): x = Foo.objects.raw("SELECT * from fooapp_foo WHERE id = %s FOR UPDATE", [self.id])[0] x.counter += 1 x.save() The pr...


python - Pygame Slow refresh rate

I have created Pygame, which has objects (balls) which randomly move around the screen and the mouse control a character which the user moves around to avoid the other objects. but the random ball that move around the screen have slow refresh rate (you can see them flashing while moving). I don't know which part of the code is to blame, the objects that move around are loaded here: ballpic = pygame....


python - How to refresh a local pip cache

Given a pip requirements file, how do you update a local cache of Python packages without installing anything or unnecessarily re-downloading packages that are currently up to date? I've tried: pip install --download="packages" --exists-action=w -r pip-requirements.txt However, it seems to automatically redownload everything, even if the correct version has already...


python - Kivy refresh image

I have an an image (kivy.uix.image.Image) instantiated with a source, but I change the source file's data. How can I refresh the image to reflect the new data?


html - Refresh a local web page using Python

I'm using Python to gather some information, construct a very simple html page, save it locally and display the page in my browser using webbrowser.open('file:///c:/testfile.html'). I check for new information every minute. If the information changes, I rewrite the local html file and would like to reload the displayed page. The problem is that webbrowser.open opens a new tab in my browser every time I run it. How...


python - django add user 404 error but refresh page ok

When I use add user in django admin site, after I click save, I got the error Page not found (404) Request Method: GET Request URL: http://192.168.11.20:8888/admin/auth/user/5/ user object with primary key u'5' does not exist. but when I refresh the page, it's gave me the right page with the same link...and it shows that I have already created the user, how could this happen?


python - Opencv window does not refresh itself at start

I have a trivial but annoying problem when I run following python code on Windows 7 64 bit OS. import sys import cv2 im = cv2.imread("D:\test.tif") ... cv2.imshow("origin",im) cv2.waitKey(0) Everything is fine except that I got gray window at first. If I move the window, then it gets refreshed and display correct image. Is this problem due to my poor graphics card, a bug in OpenCV, or some...


python - Auto refresh django form?

I have these codes in my django form. It can display datas that I wanted and can delete it. However, after deleting, I must reload the page so that I can see the data that I have deleted gone. I tried django-fresh but web server error occured. How can the django form auto refresh after deleting? Can give me some examples? <body onload="myFunction()"> <form> <h1><label for="keywords"&g...


Python won't refresh URL to receive new forex ticker data

I am trying to save updated Forex ticker data from this website: http://forex.offers4u.biz/TickDBReadDB.php?p=EURUSD just hit refresh to update the ticker. when I use my little python script, it saves the text once, but if i run it again, it makes a new file with the same old data. How can I add a "cachebreaker" so t...


python - Query refresh issue after using MySQL to load file

I use SqlAlchemy as my ORM. I do a mysqlimport cmd through subprocess. Then before and after the execution, I query the db records with the statistics_db method. But the records count results after import from CSV didn't increase. I think this is an SqlAlchemy problem. def statistics_db(f): @wraps(f) def wrapper(*args,**args2): q=Product.query.filter(&qu...


python - Using a file watch to refresh a log viewer using PyQt4

I've implemented a very simple log viewer in Python using PyQt4. I am interested in using it to follow the execution of a program, so the list view has to be refreshed when a new line is appended to the log file. Here is my implementation (without the watch): import sys from PyQt4.QtCore import * from PyQt4.QtGui import * class LogEntryModel(QAbstractListModel): def __init__(self, logfi...


python - Refresh PyDev import paths in Eclipse

I'm using Eclipse Helios under Ubuntu. Whenever I install a new library under /usr/local/lib/python2.6/dist-packages/ using pip, Eclipse doesn't see it and complains about invalid imports. I double checked the library is in place. Importing it works from the interpreter. Refreshing the PyDev configuration or restarting the IDE doesn't work. Note: the mentioned path is on the list of librar...


python - Refresh urls.py cache in django

I'm using django on nginx with FastCGI and i have a problem with urls.py. According to this question, django caches url.py file and i'm - just like above question's author - not able to modify my URLs definitions. My question is - is there any way to clear url ca...


python - How do I refresh the values on an object in Django?

I have a model object in Django. One of the methods on the object uses row-level locking to ensure values are accurate, like so: class Foo(model.Model): counter = models.IntegerField() @transaction.commit_on_success def increment(self): x = Foo.objects.raw("SELECT * from fooapp_foo WHERE id = %s FOR UPDATE", [self.id])[0] x.counter += 1 x.save() The pr...


How could i refresh a list once an item has been removed from a list within a list in python

This is quite complicated but i would like to be able to refresh a larger list once at item has been taken out of a mini list within the bigger list. listA = ['1','2','3','4','5','6','6','8','9','5','3','7'] i used the code below to split it into lists of threes split = [listA[i:(i+3)] for i in range(0, len(listA) - 1, 3)] print(split) # [['1','2','3'],['4','5','6'],['6',...


python - Pygame Slow refresh rate

I have created Pygame, which has objects (balls) which randomly move around the screen and the mouse control a character which the user moves around to avoid the other objects. but the random ball that move around the screen have slow refresh rate (you can see them flashing while moving). I don't know which part of the code is to blame, the objects that move around are loaded here: ballpic = pygame....


python - How to refresh a local pip cache

Given a pip requirements file, how do you update a local cache of Python packages without installing anything or unnecessarily re-downloading packages that are currently up to date? I've tried: pip install --download="packages" --exists-action=w -r pip-requirements.txt However, it seems to automatically redownload everything, even if the correct version has already...


python - Kivy refresh image

I have an an image (kivy.uix.image.Image) instantiated with a source, but I change the source file's data. How can I refresh the image to reflect the new data?






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top