禁用在Flask的url_for函数中转义字符 [英] disabling character escaping in Flask's url_for function

查看:222
本文介绍了禁用在Flask的url_for函数中转义字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Flask的 url_for 方法是否有一个选项来禁用自动转义?所以如果我有一个名为 getUser 的端点,路由如下: / user /< userID> ,我想调用 url_for('getUser',userID ='%'),并返回 / user /%。目前它会逃脱%symobl并发出 / user /%25 。我想这样做,因为 url_for 必须在模板编译时运行,但最终的URL是在运行javscript脚本时组成的。我将使用JavaScript字符串替换方法将 / user /%转换为 / user / abcd ,但替换我使用的脚本需要您使用符号作为占位符。

Does Flask's url_for method have an option to disable autoescaping? So if I have an endpoint called getUser with a route like this: /user/<userID>, I want to call url_for('getUser', userID='%') and have it return /user/%. Currently it will escape the % symobl and give out /user/%25. I want to do that because url_for has to run at template compile-time, but the final URL is composed when a javscript script runs. I will be using a javascript string substitution method to convert /user/% into /user/abcd, but the substitution script I'm using requires you to use a % symbol as the placeholder.

推荐答案

url_for 不支持您的用例,但假设您在Jinja模板中使用它,您只需添加一个调用 替换 删除编码:

url_for does not support your use case, but assuming you are using it inside a Jinja template you could just add a call to replace to remove the encoding:

{{ url_for('get_user', user_id='%') | replace('%25', '%') }}

或者,如果你传递URL在普通的Python代码中,您可以使用 urllib.parse.unquote (或 urllib.unquote 如果你还在Python 2):

Alternatively, if you passing the URL around in normal Python code you could use urllib.parse.unquote (or urllib.unquote if you are still on Python 2):

url = url_for('get_user', 'user_id'='%')
url = unquote(url)

这篇关于禁用在Flask的url_for函数中转义字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆