开发者

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 either None or an HttpResponse object. If it returns None, Django will continue processing this request, executing any other process_view() middleware and, then, the appropriate view. If it returns an HttpResponse object, Django won't bother calling ANY other request, view or exception middleware, or the appropriate view; it'll return that HttpResponse. 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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜