Django:分层 URL
你如何处理 Django 中的分层 URL?有什么最佳实践吗? 例如。如果我有一个像 /blog/category1/category2/myblogentry
这样的 URL(使用例如 django-mptt),你会在 urls.py
之前做一些检查还是给出视图的整个路径,让它检查每个部分是否是有效的类别等? 听起来不是那么难,但只是好奇是否有人可以推荐一些最佳实践或可以展示一些好的(通用)解决方案?
How do you deal with hierarchical URLs in Django? Any best practices for that?
Eg. If I would have an URL like /blog/category1/category2/myblogentry
(using eg. django-mptt), would you do some checking before in urls.py
or give the whole path to a view, let it check every part if it is a valid category etc?
Doesn't sound so tough, but just curious if anybody can recommend some best practices or can show some good (generic) solutions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我担心你的问题没有单一的答案。问题在于,在 URL 级别指定层次结构会捆绑太多逻辑。
我发现对用户装饰器很有用。例如,在您的情况下,您可以编写一个装饰器来检查类别的完整性,并仅将最终类别传递到视图中。像装饰器一样,可以采用具有此签名的函数:
检查每个类别确实是下一个类别的父级,并将最终检查的类别传递给视图。
如果你确实需要它是可扩展的,装饰器可以做一些内省并做出一些猜测(例如树可以有多深,剩余的参数是什么,等等)。
然后你需要做的就是仔细编写你的 URL 配置,以便装饰器获得良好的参数。
经过
I fear there is no single answer to your question. The problem is that there specifing what the hierarchy looks like at the URL level bundles too much logic with it.
I've found useful to user decorators. For example, in your case you could write a decorator that checks the sanity of categories, and passed only the final category down the view. Something like a decorator that can take a function with this signature:
Checking that each category is indeed a parent to next one, and passing down the view the final checked category.
If you really need it to be extensible, the decorator can do a bit of introspection and make some guesses (such as how deep can the tree go, what are the remaining parameters like, etc).
Then all you need to do is write your URL confs carefully, so that the decorator gets the parameters in good shape.
pass
这http://djangosnippets.org/snippets/362/也很有用。它可以解决检查 URL 是否在没有装饰器的情况下匹配。
this is http://djangosnippets.org/snippets/362/ also useful.It is allow to solve checking the if the URL matches without decorators.