Jar*_*yth 5 django view decorator url-pattern
我已经开发了自己的,但看起来这是一个非常好的事情,其他人可能首先想到它并做得更好;)
目标是能够在myapp/views.py中编写
router = Router(prefix=r'^myapp/')
@router.route(url=r'my/url/here', name="my-great-view")
def myview(request):
return render_to_response("mytemplate.html", {})
Run Code Online (Sandbox Code Playgroud)
然后在urls.py中
urlpatterns += myapp.views.router.get_patterns()
Run Code Online (Sandbox Code Playgroud)
我还内置了其他一些很酷的装饰器(@jsonview用于获取返回的字典并进行json响应,@ use_template用于获取返回的字典并将其作为上下文传递给定义的模板...)
看起来这种方式使得一切都更加本地化,可读性更强.在查看视图函数时,您不必搜索它以查找它所属的URL,或者它的"命名".
我看到了这个djangosnippet,但它比我想要的更加神奇,它看起来并不像它被普遍采用.
如果没有人将标准解决方案放在一起,我应该清理我的并向contrib提交拉取请求吗?
编辑: 如果您想要同一视图的多个网址:
@router.route(url="my-first-url", kwargs={'foo':'bar'})
@router.route(url="my-second=url", kwargs={'foo':'baz'})
def my_view(...): ...
Run Code Online (Sandbox Code Playgroud)
而当然,这并不一定是唯一做到这一点的方式-正常urlpatterns的方式大约有两份一些不错的事情,但是这两种方法并不是相互排斥的.
常规配置我们有一个主网站urls.py。并且urls.py包含名为 的变量urlpatterns。
所以我们可以将一些 url_pattern 推入其中。
from django.urls import path as djpath
URLS = []
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')
Run Code Online (Sandbox Code Playgroud)
from app.views import URLS
urlpatterns.extend(URLS)
Run Code Online (Sandbox Code Playgroud)