问题
I am from the Java Hibernate and Symfony2 background where I used to write the routing within the controller on the top of function like this:
/**
* @Route("/blog")
*/
class PostController extends Controller
{
I know its not available in Django but is there any way I can code some decorator etc. so that I can mention the URL like this:
@URL("/mytest")
class myView():
pass
回答1:
While it would be very undjangonic, you could try something like this:
project/
decorators.py
views.py
urls.py
# decorators.py
from django.conf import settings
from django.utils.importlib import import_module
from django.conf.urls.defaults import patterns, url
def URL(path):
path = r'^%s$' % path[1:] # Add delimiters and remove opening slash
def decorator(view):
urls = import_module(settings.ROOT_URLCONF)
urls.urlpatterns += patterns('', url(path, view))
return view
return decorator
# views.py
from .decorators import URL
@URL('/')
def home(request):
# your view
@URL('/products')
def products(request):
# your view
# urls.py
from django.conf.urls import patterns
from . import views # import the modules with your views
urlpatterns = patterns('',) # create an empty url dispatcher to append to
And make sure every file containing this decorator is imported before processing urls (e.g. by importing them in the urls file).
来源:https://stackoverflow.com/questions/13638326/is-there-any-way-that-i-can-write-url-in-django-using-annotations-in-python