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

落爺英雄遲暮 提交于 2019-12-04 20:15:46

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).

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