How can I share a dict between two different http requests

不想你离开。 提交于 2020-01-14 05:21:28

问题


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])

回答1:


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.




回答2:


Binding the dictionary to a global name will make it persist for as long as the Django project runs. Note that each Django process (some WSGI containers, e.g. mod_wsgi, can run multiple processes for an app) will have its own independent copy of the dictionary.




回答3:


If the data is relevant to the user, you can use djanog's session framework to persist data across requests. If the data needs to be shared between numerous users, you can use the cache.



来源:https://stackoverflow.com/questions/11999198/how-can-i-share-a-dict-between-two-different-http-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!