Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我如何隐藏id序列并提供一个;友好的;使用金字塔的url?_Python_Url_Url Rewriting_Url Routing_Pyramid - Fatal编程技术网

Python 我如何隐藏id序列并提供一个;友好的;使用金字塔的url?

Python 我如何隐藏id序列并提供一个;友好的;使用金字塔的url?,python,url,url-rewriting,url-routing,pyramid,Python,Url,Url Rewriting,Url Routing,Pyramid,我在数据库中有一个列表,希望在被访问时隐藏主键的序列,使其不显示在url中。所以我想把这样的事情转过来: example.com/post/9854 为此: example.com/post/one-two-three-four 显然,在查询中仍然使用主键。实现这一点的金字塔方式是什么 这个“用户友好的URL片段”通常被称为“slug”,我认为它来自于报纸排版时的“slug” 您通常会在模型中添加一个字段来存储段塞。字段应该是唯一的和索引的(您甚至可以考虑将它作为您的模型的主键,这取决于您所

我在数据库中有一个列表,希望在被访问时隐藏主键的序列,使其不显示在url中。所以我想把这样的事情转过来:

example.com/post/9854
为此:

example.com/post/one-two-three-four
显然,在查询中仍然使用主键。实现这一点的金字塔方式是什么

这个“用户友好的URL片段”通常被称为“slug”,我认为它来自于报纸排版时的“slug”

您通常会在模型中添加一个字段来存储段塞。字段应该是唯一的和索引的(您甚至可以考虑将它作为您的模型的主键,这取决于您所处的伟大的“自然与代理主键”辩论:)(

)。 当你的文章第一次被保存时,你会从文章的标题中生成一次slug,并且永远不会再更改它,即使标题发生了变化——这对于SEO和链接很重要

class Post(Base)
    ...
    def __init__(self, title, body):
        self.slug = generate_slug(title)
        self.title = title
        self.body = body
然后,在视图代码中,使用slug在数据库中查找post,就像使用主键一样

   def my_view(request):
       slug = request.matchdict['slug']
       post = DBSession.query(Post).filter(Post.slug==slug).one()
       ...
您正在考虑的URL模式要求所有帖子的所有slug都必须是唯一的,这可能会让人恼火。如果您查看许多新闻网站,您会注意到它们使用“组合”URL方案,其中主键和slug都存在于URL中:

/posts/123/one-two-three-four
/posts/123-one-two-three-four
etc.

主键用于在数据库中查找数据,slug部分纯粹用于SEO和可读性

如果你理解正确,我想你会想使用cookies。使用您的键值设置cookie。
/posts/123/one-two-three-four
/posts/123-one-two-three-four
etc.