您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

详解Python的Django框架中的中间件

2025/12/9 4:06:03发布27次查看
什么是中间件
我们从一个简单的例子开始。
高流量的站点通常需要将django部署在负载平衡proxy之后。 这种方式将带来一些复杂性,其一就是每个request中的远程ip地址(request.meta[remote_ip])将指向该负载平衡proxy,而不是发起这个request的实际ip。 负载平衡proxy处理这个问题的方法在特殊的 x-forwarded-for 中设置实际发起请求的ip。
因此,需要一个小小的中间件来确保运行在proxy之后的站点也能够在 request.meta[remote_addr] 中得到正确的ip地址:
class setremoteaddrfromforwardedfor(object): def process_request(self, request): try: real_ip = request.meta['http_x_forwarded_for'] except keyerror: pass else: # http_x_forwarded_for can be a comma-separated list of ips. # take just the first one. real_ip = real_ip.split(,)[0] request.meta['remote_addr'] = real_ip
(note: although the http header is called x-forwarded-for , django makes it available as request.meta['http_x_forwarded_for'] . with the exception of content-length and content-type , any http headers in the request are converted to request.meta keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an http_ prefix to the name.)
一旦安装了该中间件(参见下一节),每个request中的 x-forwarded-for 值都会被自动插入到 request.meta['remote_addr'] 中。这样,django应用就不需要关心自己是否位于负载平衡proxy之后;简单读取 request.meta['remote_addr'] 的方式在是否有proxy的情形下都将正常工作。
实际上,为针对这个非常常见的情形,django已将该中间件内置。 它位于 django.middleware.http 中, 下一节将给出这个中间件相关的更多细节。
安装中间件
要启用一个中间件,只需将其添加到配置模块的 middleware_classes 元组中。 在 middleware_classes 中,中间件组件用字符串表示: 指向中间件类名的完整python路径。 例如,下面是 django-admin.py startproject 创建的缺省 middleware_classes :
middleware_classes = ( 'django.middleware.common.commonmiddleware', 'django.contrib.sessions.middleware.sessionmiddleware', 'django.contrib.auth.middleware.authenticationmiddleware',)
django项目的安装并不强制要求任何中间件,如果你愿意, middleware_classes 可以为空。
这里中间件出现的顺序非常重要。 在request和view的处理阶段,django按照 middleware_classes 中出现的顺序来应用中间件,而在response和异常处理阶段,django则按逆序来调用它们。 也就是说,django将 middleware_classes 视为view函数外层的顺序包装子: 在request阶段按顺序从上到下穿过,而在response则反过来。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product