Django:分层 URL

发布于 2024-09-07 16:13:29 字数 237 浏览 4 评论 0原文

你如何处理 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

最佳男配角 2024-09-14 16:13:29

我担心你的问题没有单一的答案。问题在于,在 URL 级别指定层次结构会捆绑太多逻辑。

我发现对用户装饰器很有用。例如,在您的情况下,您可以编写一个装饰器来检查类别的完整性,并仅将最终类别传递到视图中。像装饰器一样,可以采用具有此签名的函数:

f(request, cat1, catN..., slug)

检查每个类别确实是下一个类别的父级,并将最终检查的类别传递给视图。

@validate_category_hierarchy
def post_in_category(request, category, slug):

如果你确实需要它是可扩展的,装饰器可以做一些内省并做出一些猜测(例如树可以有多深,剩余的参数是什么,等等)。

然后你需要做的就是仔细编写你的 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:

f(request, cat1, catN..., slug)

Checking that each category is indeed a parent to next one, and passing down the view the final checked category.

@validate_category_hierarchy
def post_in_category(request, category, slug):

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

故事和酒 2024-09-14 16:13:29

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文