2

我来自 Java Hibernate 和 Symfony2 背景,我曾经在这样的函数顶部的控制器内编写路由:

/**
 * @Route("/blog")
 */
class PostController extends Controller
{

我知道它在 Django 中不可用,但有什么方法可以编写一些装饰器等,以便我可以像这样提及 URL:

@URL("/mytest")
class myView():
    pass
4

1 回答 1

3

虽然它会非常 undjangonic,但你可以尝试这样的事情:

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

并确保在处理 url 之前导入包含此装饰器的每个文件(例如,通过在 urls 文件中导入它们)。

于 2012-11-30T03:20:58.023 回答