使用带斜杠的 python quote_plus

dis*_*ive 5 python urllib flask

我正在使用quote_plusfromurllib与它的表兄弟一起工作得很好unquote_plus,以便在空间之间产生优势,这样:The Cat Sat变得The+Cat+Sat很棒。然而现在的问题是,使用这个会影响路径,当我变成/description/id/34/the cat sat on这样的时候

%2Fdescription%2F274%2Fthe+cat+sat+on
Run Code Online (Sandbox Code Playgroud)

我应该怎么办。我真的想要空格的加号,但我在只替换加号的空格之间左右为难。在建立道路时是否有适当的治疗方法?我真的很想保留斜杠和加号。

烧瓶模板视图:

<a href="{{animal.url|quote_plus}}">{{animal.title}}</a>
Run Code Online (Sandbox Code Playgroud)

在代码.py中:

animal["url"] = "/description/"+str(animal["id"]) + "/" + animal["title"]
Run Code Online (Sandbox Code Playgroud)

还:

app.jinja_env.filters['quote_plus'] = lambda u: quote_plus(u)
Run Code Online (Sandbox Code Playgroud)

Ken*_*rom 5

当您调用 quote_plus 时,设置 safe='/',这就是您所要求的。

查看文档https://docs.python.org/3/library/urllib.parse.html 请注意,quote 有一个默认参数 safe='/',而 quote_plus 有一个默认参数 safe=''

urllib.parse.quote(string, safe='/', encoding=None, errors=None)
urllib.parse.quote_plus(string, safe='', encoding=None, errors=None)
Run Code Online (Sandbox Code Playgroud)

差异如下所示:

url = '/description/id/34/the cat sat on'
print 'quote: ', urllib.quote(url)
print 'quote_plus: ', urllib.quote_plus(url)
print 'quote_plus with safe set: ', urllib.quote_plus(url, safe='/')
Run Code Online (Sandbox Code Playgroud)

输出

quote:  /description/id/34/the%20cat%20sat%20on
quote_plus:  %2Fdescription%2Fid%2F34%2Fthe+cat+sat+on
quote_plus with safe set:  /description/id/34/the+cat+sat+on
Run Code Online (Sandbox Code Playgroud)