Django 1.10:“新样式";相当于`process_request()`的中间件 [英] Django 1.10: "new style" middleware equivalent of `process_request()`
本文介绍了Django 1.10:“新样式";相当于`process_request()`的中间件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
一个人如何创建新样式"中间件,该中间件实现与将 process_request()
钩子与旧样式"挂钩等效的实现方式?
How would one create "new style" middleware, which fulfills an equivalent implementation to using the process_request()
hook with the "old style"?
我已经使用 MiddlewareMixin
...
from django.utils.deprecation import MiddlewareMixin
class MyCustomMiddleware(MiddlewareMixin):
def process_request(self, request):
# My request logic
return response
我想知道如何执行纯"> 1.9新样式"实现.我尝试通过这样实现 __ init __()
和 __ call __()
来做到这一点,但是没有运气:
I'd like to know how to do a "pure" >1.9 "new style" implementation. I tried doing so by implementing __init__()
and __call__()
like this without luck:
class MyCustomMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
# My request logic
return response
谢谢.
推荐答案
下面是一个示例...
Here an example...
class TimeStampMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
request.timestamp = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
response = self.get_response(request)
return response
现在,您可以从您的视图中获取每个请求中的时间戳记!(仅是一个例子)
Now you can get the timestamp in every request from yours views! (is only an example)
这篇关于Django 1.10:“新样式";相当于`process_request()`的中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文