The Django application loads data from a file to a Python dict, process it and sends it as http response. Now say n number of request are received on the web server then this Django app would run n times and load data from a file to a Python dict n times. I was wondering if somehow I can make this data being loaded to the dict only once while n http response could be served.
An example view.py file for the problem situation can be as followed:
from django.http import HttpResponse
from django.http import HttpRequest
def hello(request):
data = open("abc").readlines()
return HttpResponse(data[0])
This is a job for the Django Middleware. Add it to your settings and it will persist across your request. Its a better option then persistence and definitely a lot better than using a global object.
Middleware is a framework of hooks into Django’s request/response processing. It’s a light, low-level “plugin” system for globally altering Django’s input and/or output. Each middleware component is responsible for doing some specific function. For example, Django includes a middleware component, XViewMiddleware, that adds an “X-View” HTTP header to every response to a HEAD request.