Задать вопрос

Тел: +7 965 3737 888

526

Просмотров

4

Ответов

Url filter middleware

<h2>How to config it</h2>
<p>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:</p>
FILTERS = (
    (r'^user/(?P&lt;user_id&gt;\d+)/', 'apps.users.filter.check_valid_user'),
)

<p>FILTERS should be a list or tuple with two elements tuple item. The format should be like:</p>
(url_patterns, function)

<p>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:</p>
r'^user/(?P&lt;user_id&gt;\d+)/'

<p>So you can see, you can set parameter name user_id, then it'll be passed to the function behind.</p>
<p>Function can be a string format, just like above example, and it can be also a real function object.</p>
<p>It'll only impact request.</p>
<h2>How to write filter function</h2>
<p>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:</p>
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!')})

<p>I think the code is very clear. </p>
<p>And you can use it filtermiddleware to do like user authentication check, and other checking for url.</p>
<p>BTW, render_template is comes from <a href="http://foothold.ru/knowledge/detail/render-template-shortcut.html">Snippets #4</a></p>

Вопрос полезен? Да0/Нет0
file_3823.py(870.0б)
None

Ответы (4):

Ответronnypfannschmidt:31.03.2007
Ответ полезен? Да0/Нет0

you could just use a new urlconf for that stuff

Ответjerry2801:23.10.2009
Ответ полезен? Да0/Нет0

i think this plan is not the best~

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

jerry2801@gmail.com

Ответlimodou:04.03.2007
Ответ полезен? Да0/Нет0

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.

Ответwiz:04.03.2007
Ответ полезен? Да0/Нет0

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