编码 URL 路径并在浏览器中显示

Encode URL path and show it in browser

我用django搭建了一个博客网站。我使用 python urllib.quote 函数对 url 字符串进行编码,而无需提交表单。例如,在我的 html 文件中,有这样的 href link:

http://example.com/post/?tag=new%20tag  (1)

(1) 是我从 (2) 编码的 link:

  http://example.com/post/?tag=new tag  (2)

这与表单 GET 方法略有不同,其中 "new tag" 被编码为 "new+tag"。只要输出 url 不包含 space,两者都适合我。

但是,在我点击我的网页中的 link (1) 后,浏览器中生成的 url 看起来像 link (2)(带有 space ).我应该把我的 link 保留为 (2) 吗?我怎样才能使输出 url 成为 (1) 或以下标准输出:

 http://example.com/post/?tag=new+tag  (3)

您可以使用 urlencode:

 >>> import urllib
 >>> urllib.urlencode({'tag': 'new tag'})
'tag=new+tag'

您应该改为使用 urllib.quote_plus 来回编码。

https://docs.python.org/2/library/urllib.html#urllib.quote_plus