如何在两个不同的http请求之间共享字典 [英] How can I share a dict between two different http requests

查看:53
本文介绍了如何在两个不同的http请求之间共享字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django应用程序将数据从文件加载到Python字典,进行处理并将其作为http响应发送.现在说,在Web服务器上接收到n个请求,那么这个Django应用程序将运行 n 次,并将数据从文件加载到Python dict n 次.我想知道是否可以在可以提供 n http响应的同时,仅一次将数据加载到dict.

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.

针对问题情况的示例 view.py 文件可以如下所示:

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.

中间件是挂钩Django请求/响应处理的框架.这是一个轻量级的插件"系统,用于全局更改Django的输入和/或输出.每个中间件组件负责执行某些特定功能.例如,Django包括一个中间件组件XViewMiddleware,该组件在对HEAD请求的每个响应中都添加了"X-View" HTTP标头.

这篇关于如何在两个不同的http请求之间共享字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆