On Fri, Sep 09, 2016 at 10:11:25PM -0700, Chris Seberino wrote: > 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?
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 -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20160910112946.GO6601%40koniiiik.org. For more options, visit https://groups.google.com/d/optout.
signature.asc
Description: Digital signature