Is there any way that I can write URL in django using annotations in python

半城伤御伤魂 提交于 2019-12-06 16:01:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!