Django URL 设计
我经常发现自己陷入了一个对自己提出的 URL 不太确定的世界。我认为这主要是因为我有一些关于 django 中的 URL 设计的问题尚未得到解答。
比如说,我为我的网站用户建立了一个公共个人资料页面。可以通过提供用户 ID 来访问它。用户 ID 应该是 URL 的一部分(即 /profile/
),还是应该在查询字符串中提供(/profile?userid=
我在我的项目中广泛使用 AJAX。 AJAX URL 的设计是否应该与其对应部分不同?是否有用于此目的的设计模式?
I often find myself falling into a world in which I am not so sure about the URLs that I came up with. I think that's mainly because I have a few questions regarding URL design in django that remain unanswered.
Say, I have built a public profile page for my site users. It can be accessed by providing an user id. Should the user id be part of the URL (ie. /profile/<userid>/
) or should it be provided in the querystring (/profile?userid=<userid>
)? And why?
I use AJAX extensively in my project. Should the AJAX URLs be designed differently from their counterparts? Is there a design pattern for this purpose?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这里没有任何硬性规定。我想说,任何相当静态的内容都应该使用
/profile//
格式。 GET 参数 -?userid=
- 应该保留给那些更动态、难以编码为 URL 一部分的内容(例如一组搜索词),或者当您一次需要多个参数,并且不能依赖顺序。There isn't any hard-and-fast rule here. I'd say that anything which is reasonably static should use the
/profile/<userid>/
format. GET parameters -?userid=<userid>
- should be reserved for things that are more dynamic, are just difficult to encode as part of the URL (such as a set of search terms), or when you need several parameters at once and can't count on the order.Django 不鼓励使用查询字符串并鼓励使用漂亮的 URL。您只需在
URLconf
中正确设置它们即可。如果您还没有阅读Django Book(可以在线免费获取),那么您应该阅读。它在第3章中讨论了这一点:本章详细介绍了如何以及为何这样做!
Django discourages the use of query strings and encourages the use of pretty URLs. You just have to set them up properly in your
URLconf
. If you haven't read the Django Book (available freely online), you should. It talks about this in chapter 3:This chapter details how and why to do this!
前段时间我也有同样的疑问,我公司的项目负责人对我说:
“尽量避免无限量不同的URL”
所以,如果某个参数可以生成无限量不同的URL,那么应该是作为参数发送(例如:.com?param=),例如时间戳。有无数个不同的时间戳,所以它应该是一个参数。
另一方面,有些值是有界的,例如一个对象 ID。如果将 和 ID 放入 URL,在最坏的情况下,您可以生成与 ID 相同数量的 URL,但不会生成无限的 URL。在这种情况下,ID 可以包含在 URL 中(如下所示:.com/content//view)
这个简单的短语对我帮助很大,我希望你也是=)
I had the same doubt some time ago, and the project leader of my company said me:
"Try to avoid infinite amount of differents URLs"
So, if some parameter can generate infinite differents URLs, it should be send as a parameter (like this: .com?param=), for example a timestamp. There is infinite amount of differents timestamps, so it should be a paramenter.
In the other hand there are values that are bounded, for example one object ID. If you put and ID in the URL, in the worst case you can generate the same amounts of URLs than IDs, but not infinite URLs. In this case the ID can be included in the URL (like this: .com/content//view)
This simple phrase helped me a lot, I hope you too =)