List Info

Thread: Tip:decorator and urls.py




Tip:decorator and urls.py
user name
2006-12-29 02:40:16
This subject is not a bug report or enhancement proposal,
just a tip,
and I'v began to use it.

What I want to say?
==================

I think many django users know that you can use decorator in
the view,
just like:

------------------------------------------------------------
-8<--------------------------------------
check_userid
def list(request, user_id):
    ...
------------------------------------------------------------
->8--------------------------------------

So using decorator, you can split individual functionalities
into
pieces, and reuse them as decorators, or simple as:

------------------------------------------------------------
-8<--------------------------------------
def list(request, user_id):
   ...
list = check_userid(list)
------------------------------------------------------------
->8--------------------------------------

And for now, in the trunk, you can even use function objects
in the
urls, just like:

------------------------------------------------------------
-8<--------------------------------------
from django.conf.urls.defaults import *
from yourapp.views import func

urlpatterns = patterns('',

    (r'^$', func),
)
------------------------------------------------------------
->8--------------------------------------

So this a great thing!

We can make many tricks on it. And I want to introduce how
to use
decorator on it.
Very simple!

Say you put check_userid in a module named decorator.py, and
the
urls.py could be:

------------------------------------------------------------
-8<--------------------------------------
from django.conf.urls.defaults import *
from yourapp.views import func
from decorator import check_userid

urlpatterns = patterns('',

    (r'^$', check_userid(func)),
)
------------------------------------------------------------
->8--------------------------------------

So you see, you can move the decorator from the views into
urls.py.
And I think  sometimes urls.py is the very suitable place do
these
things, just like: permission checking, environment
checking,
exception handling, even we can think about template
rendering in
here.

Some examples
===============

I'v finished several decorators, for example:

------------------------------------------------------------
-8<--------------------------------------
class HttpRedirectException(Exception):pass

# render_template
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.http import HttpResponseRedirect

def template(templatename):
    """
    render the func's result into a template
    """

    def _render(func=None):
        exceptionhandle
        def _f(*args, **kwargs):
            if func:
                result = func(*args, **kwargs)
            else:
                result = {}
            return render_to_response(templatename,
context_instance=RequestContext(args[0], result))
        return _f
    return _render

from django.conf import settings

def exceptionhandle(func):
    """
    Catch Special Exception and deal with them
    """
    def _f(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except HttpRedirectException, e:
            return HttpResponseRedirect(str(e))
    return _f
------------------------------------------------------------
->8--------------------------------------

If you use template decorator, you can just return your data
from the
view function, for example:

------------------------------------------------------------
-8<--------------------------------------
template('template.html')
def list(requst):
    objs = User.objects.all()
    return objs
------------------------------------------------------------
->8--------------------------------------

And if you want to use decorator in urls.py you can write
it:

------------------------------------------------------------
-8<--------------------------------------
from django.conf.urls.defaults import *
from yourapp.views import list
from decorator import template

d_list = template('template.html')
urlpatterns = patterns('',

    (r'^$', d_list(list)),
)
------------------------------------------------------------
->8--------------------------------------

So you may ask what's the benefits of it. So I think there
are many benefits:

1. You can make the control centralized management
2. Reuse is more easy, because the common app can only
return the data
but not the rendered html text, so change the output will be
easy.
3. others, I don't think so much

Because you can only return data, but not html text, so you
can use
decorator to render the result with template or json(ajax
support), so
that it can support both html and json.

From the above template decorator, you can see it invoke
another
exceptionhandle decorator, and this decorator can catch a
HttpRedirectException exception, so you can write your view
just like:

------------------------------------------------------------
-8<--------------------------------------
template('template.html')
def list(request):
    if success:
        #return HttpResponseRedirect('url')
        raise HttpRedirectException
    else:
        return errorinfo
------------------------------------------------------------
->8--------------------------------------

So you can use template to deal with two type different
output:
redirect and normal render output. Of course, template just
my
implementation and I just want to use it to describe some
example.
Just some tips, you can do anything what you want if django
supports
it.

I hope you have fun with decorator.

-- 
I like python!
UliPad <<The Python Editor>>: http://wiki
.woodpecker.org.cn/moin/UliPad
My Blog: http://www.donews.net/l
imodou

--~--~---------~--~----~------------~-------~--~----~
 You received this message because you are subscribed to the
Google Groups "Django users" group.
To post to this group, send email to django-usersgooglegroups.com
To unsubscribe from this group, send email to
django-users-unsubscribegooglegroups.com
For more options, visit this group at htt
p://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

[1]

about | contact  Other archives ( Real Estate discussion Medical topics )