How modify Django to set URLs with decorators on the view functions like Flask? (rather than using urls.py)

70 views
Skip to first unread message

Chris Seberino

unread,
Sep 10, 2016, 1:11:25 AM9/10/16
to Django users
Flask has a neat design where instead of having a urls.py file they bind URLs to view functions with decorators.

Possible to do something similar with Django?  What modifications would be needed?

Thanks,

cs

Michal Petrucha

unread,
Sep 10, 2016, 7:30:59 AM9/10/16
to django...@googlegroups.com
Personally, I'm not a big fan of the standard Flask pattern where URL
routing is set up as a side effect of importing view modules, rather
than having an explicit place that reliably defines the exact list of
patterns that will be used in a clearly-defined order no matter what.
The Flask pattern leaves a lot of room for inconsistent behavior
across processes, depending on the order in which the modules
containing views were imported.

That being said, you can easily put something like this into your
``mysite/urls.py``::

from django.conf.urls import url

urlpatterns = []

def route(pattern, **kwargs):
def inner(view_function):
urlpatterns.append(url(pattern, view_function, **kwargs))
return view_function

Then, you'd just import the route decorator, and define your views
like this::

from mysite.urls import route


@route(r'^/neat-view/$', name='neat')
def my_view(request):
return HttpResponse("Neat!")


If you feel like it, you can go wild, and do some more hand stuff in
there, like inspect the function's name, and automatically register
the pattern with the same name, or possibly even more cool stuff.

Keep in mind that if you do something like this, you're going against
established patterns in the Django world, which will make your
application harder to understand for people who are already familiar
with the way one does routing with Django.

Django itself has been steadily moving away from doing import-time
side-effect magic, towards handling application initialization as
explicitly as possible, and for good reason. Explicit initialization
does not rely on coincidental circumstances, like the order of import
statements, and makes it possible to detect errors early on and fail
immediately, instead of running in a semi-broken state happily without
ever telling anyone.

Cheers,

Michal
signature.asc
Reply all
Reply to author
Forward
0 new messages