Django Middleware: How do I access a view's params from middleware
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 functio开发者_开发技巧n runs (something that I need from the URL though).
You will have to implement the process_view
method.
It has this signature:
process_view(self, request, view_func, view_args, view_kwargs)
and is executed before the view function is called:
process_view()
is called just before Django calls the view. It should return eitherNone
or anHttpResponse
object. If it returnsNone
, Django will continue processing this request, executing any otherprocess_view()
middleware and, then, the appropriate view. If it returns anHttpResponse
object, Django won't bother calling ANY other request, view or exception middleware, or the appropriate view; it'll return thatHttpResponse
. Response middleware is always called on every response.
Then you should be able to access arg1
and arg2
with:
class MyMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
arg1, arg2 = view_args[:2]
You can access URL parameters in the middleware's __call__
, process_request
or process_response
methods by using resolve()
like this:
from django.urls import resolve
class MyMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
match = resolve(request.path_info)
arg1, arg2 = match.args[:2]
# do something with arg1, arg2
return self.get_response(request)
精彩评论