Django 中间件:如何从中间件访问视图的参数
假设我有一个视图:
def pony_view(request, arg1, arg2):
... Make ponies, etc ...
和一个中间件:
class MyMiddleware(object):
def process_request(request):
# How do I access arg1, arg2 here?
当然 arg1 和 arg2 将通过 URL 参数和 urls.py 传入。
我需要这样做的原因是因为我想在视图函数运行之前向 request.session 添加一些内容(不过我需要从 URL 中获取一些内容)。
Let's say I have a view:
def pony_view(request, arg1, arg2):
... Make ponies, etc ...
And a middleware:
class MyMiddleware(object):
def process_request(request):
# How do I access arg1, arg2 here?
Of course arg1, and arg2 will be passed in via URL params with urls.py.
The reason I need to do this is because I want to add something to request.session before the view function runs (something that I need from the URL though).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须实施
process_view
方法。它具有以下签名:
并在调用视图函数之前执行:
然后您应该能够通过以下方式访问
arg1
和arg2
:You will have to implement the
process_view
method.It has this signature:
and is executed before the view function is called:
Then you should be able to access
arg1
andarg2
with:如果你想从 URL 读取 GET 参数,你可以使用 request.GET 字典:
If you want to read GET parameters from URL you can use request.GET dictionary:
您可以使用
resolve()
访问中间件的__call__
、process_request
或process_response
方法中的 URL 参数,如下所示:You can access URL parameters in the middleware's
__call__
,process_request
orprocess_response
methods by usingresolve()
like this: