为什么不自己做呢? 在制作时,请注意了解 urllib.urlencode、urllib.quote 和 urllib.quote_plus 之间的关系。
对我来说,我最终制作了一个可以用作过滤器和可调用函数的函数(为烧瓶应用程序完成):
@app.template_filter('urlencode')
def urlencode(uri, **query):
parts = list(urlparse.urlparse(uri))
q = urlparse.parse_qs(parts[4])
q.update(query)
parts[4] = urllib.urlencode(q)
return urlparse.urlunparse(parts)
app.jinja_env.globals['urlencode'] = urlencode
在模板中作为函数使用:
{% set vendor_url = urlencode('http://www.google.com/search', q=adset.keyword.text) %}
在模板中用作过滤器:
{% set vendor_url = 'http://www.google.com/search?q=%s' % querytext %}
{{ vendor_url|urlencode }}
为什么不自己做呢?
因为 jinja2 已经有很多内置过滤器(http://jinja.pocoo.org/docs/templates/#builtin-filters),而 urlencode 是一个经典功能,可以附加到内置过滤器中。
问候,
斯蒂芬妮
urllib.quote_plus(uri)
如果这可以提交到主版本,那就太好了。 在 jinja2 这样完整的模板系统中,这是人们所期望的。
@radekstepan @gfuchedzhy我的印象是它不像通过引号或引号加上传递字符串/标记那么简单。 就我而言,这导致了quote_plus 中的unicode 问题。 似乎必须将 unicode 编码为 utf-8 才能与 quote_plus() 很好地配合使用。 这是我的解决方案:
@app.template_filter('urlencode')
def urlencode_filter(s):
if type(s) == 'Markup':
s = s.unescape()
s = s.encode('utf8')
s = urllib.quote_plus(s)
return Markup(s)
对于任何偶然发现此过滤器并寻找urlencode
过滤器的人,它于 2012 年在 06a8b1c02b2091b31ef4f39ddde3184f25f58260 和 5145401fe5f9995a32757f34359623b87048ab8b 中添加。 #85 中的讨论。
它被称为urlencode
而不是urlquote
、 urlquoteplus
、 urlquote_plus
或urlescape
(为其他通过搜索登陆的人添加这些)。
最有用的评论
对于任何偶然发现此过滤器并寻找
urlencode
过滤器的人,它于 2012 年在 06a8b1c02b2091b31ef4f39ddde3184f25f58260 和 5145401fe5f9995a32757f34359623b87048ab8b 中添加。 #85 中的讨论。它被称为
urlencode
而不是urlquote
、urlquoteplus
、urlquote_plus
或urlescape
(为其他通过搜索登陆的人添加这些)。