Is there a standard way of replacing urlpatterns with view decorators in django? Is there a standard way of replacing urlpatterns with view decorators in django? django django

Is there a standard way of replacing urlpatterns with view decorators in django?


The regular configuration we have a main website urls.py . And the urls.py contains variable named urlpatterns.

so wo can push some url_pattern into it.

app/views.py

from django.urls import path as djpathURLS = []URLS_d = {}def route(path=''):    def wrapper(func):        path_name = path or func.__name__        URLS.append(            djpath(path_name, func)        )        ### below is not important ####        path_func = URLS_d.get(path_name, None)        if path_func:            print(path_func, '<>', func)            raise Exception('THE same path')        URLS_d[path_name] = func        ### above is not important ####    return wrapper@route()def index(req):    return HttpResponse('hello')

website/urls.py

from app.views import URLSurlpatterns.extend(URLS)


If you use class base view , you can use django-request-mapping,

A Simple Example
  • view.py
from django_request_mapping import request_mapping@request_mapping("/user")class UserView(View):    @request_mapping("/login/", method="post")    def login(self, request, *args, **kwargs):        return HttpResponse("ok")    @request_mapping("/signup/", method="post")    def register(self, request, *args, **kwargs):        return HttpResponse("ok")    @request_mapping("/<int:user_id>/role/")    def get_role(self, request, user_id):       return HttpResponse("ok")     @request_mapping("/<int:pk/", method='delete')    def delete(self, request, pk):        User.objects.filter(pk=pk).delete()        return HttpResponse("ok")@request_mapping("/role")class RoleView(View):    # ...
  • urls.py
from django_request_mapping import UrlPatternurlpatterns = UrlPattern()urlpatterns.register(UserView)urlpatterns.register(RoleView)

and request urls are:

post:  http://localhost:8000/user/login/post:  http://localhost:8000/user/signup/get:  http://localhost:8000/user/1/role/delete: http://localhost:8000/user/1/# ...