disabling character escaping in Flask's url_for function

折月煮酒 提交于 2019-12-07 02:50:52

问题


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.


回答1:


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', '%') }}

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)


来源:https://stackoverflow.com/questions/27300332/disabling-character-escaping-in-flasks-url-for-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!