Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to access URL regex parameters inside a middleware class?

I am working on a Django project on Google App Engine. I have a URL like:

http://localhost:8080/[company]/projects/project

Note that [company] is a URL parameter defined in my urls.py like:

(r'(^[a-zA-Z0-9-_.]*)/projects/project/(\d*)', 'projects.views.project_form'),

I want to get the value of [company] from a middleware where I will set the GAE datastore namespace to the [company] value.

Is it possible to get the [company] parameter from the request object passed in the process_request method of middleware class?

like image 332
Muhammad Towfique Imam Avatar asked Aug 02 '12 10:08

Muhammad Towfique Imam


1 Answers

If you are using the process_view middleware, you will have access to the views arguments and therefore the company value. Have a look at the function's definition:

def process_view(self, request, view_func, view_args, view_kwargs)
    ...

view_args is a list of positional arguments that will be passed to the view, and view_kwargs is a dictionary of keyword arguments that will be passed to the view.

so you should just be able to grab it from there, something like:

def process_view(self, request, view_func, view_args, view_kwargs):
    company = view_kwargs.get('company', None)

Here's some more info from the django book on how the named and unnamed groups in your urls translate to args and kwargs in your view:

http://www.djangobook.com/en/1.0/chapter08/#cn38

particularly

This [named url groups] accomplishes exactly the same thing as the previous example, with one subtle difference: the captured values are passed to view functions as keyword arguments rather than positional arguments.

like image 182
Timmy O'Mahony Avatar answered Oct 24 '22 07:10

Timmy O'Mahony