Login

Url filter middleware

Author:
limodou
Posted:
March 3, 2007
Language:
Python
Version:
Pre .96
Score:
2 (after 4 ratings)

How to config it

You can treat it as a micro url filter framework. Before you using it, you should setup some options about it. The option entry shoud be like this:

FILTERS = (
    (r'^user/(?P<user_id>\d+)/', 'apps.users.filter.check_valid_user'),
)

FILTERS should be a list or tuple with two elements tuple item. The format should be like:

(url_patterns, function)

And url_patterns could be a single regex expression or a list/tuple regex expressions, So you can set multi regex expression in it. And the regulation is just like url dispatch, as above example, the url pattern is:

r'^user/(?P<user_id>\d+)/'

So you can see, you can set parameter name user_id, then it'll be passed to the function behind.

Function can be a string format, just like above example, and it can be also a real function object.

It'll only impact request.

How to write filter function

According above example, I define a url pattern, and what to check if the user is a valid user, and if the user is visiting his own urls, so the filter function could be:

from django.contrib.auth.models import User
from utils.common import render_template

def check_valid_user(request, user_id):
    if request.user.is_anonymous():
        return render_template(request, 'users/user_login.html', {'next':'%s' % request.path})
    try:
        person = User.objects.get(pk=int(user_id))
    except User.DoesNotExist:
        return render_template(request, 'error.html', {'message':_("User ID (%s) is not existed!") % user_id})
    if person.id != request.user.id:
        return render_template(request, 'error.html', {'message':_('You have no right to view the page!')})

I think the code is very clear.

And you can use it filtermiddleware to do like user authentication check, and other checking for url.

BTW, render_template is comes from Snippets #4

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Author: [email protected]
# version: 0.1
# Url filter middleware
# Update:
#   0.1

from django.conf import settings
from utils.common import get_func
import re

class FilterMiddleware(object):
    def process_request(self, request):
        filter_items = getattr(settings, 'FILTERS', ())
        for v in filter_items:
            r, func = v
            if not isinstance(r, (list, tuple)):
                r = [r]
            for p in r:
                if isinstance(p, (str, unicode)):
                    p = re.compile(p)
                m = p.match(request.path[1:])
                if m:
                    kwargs = m.groupdict()
                    if kwargs:
                        args = ()
                    else:
                        args = m.groups()
                    return get_func(func)(request, *args, **kwargs)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

wiz (on March 4, 2007):

I guess re.compile(p) stuff should be in __init__ method. Is there is a special need to recompile filters for each request? (;

#

limodou (on March 4, 2007):

Because I don't know if the instance of Middleware will be created per request, if it doesnot, put re.compile(p) in init will have problem. And the url in FILTERS can be not the same as urls.py(of cause they can be the same), and you can pass string or instance of re.compile() to it, if the object is string, this middleware will compile it first.

#

RonnyPfannschmidt (on March 31, 2007):

you could just use a new urlconf for that stuff

#

jerry2801 (on October 23, 2009):

i think this plan is not the best~

如果楼主有心的方法,希望可以发生一份给我,谢谢!

[email protected]

#

Please login first before commenting.