J-bob
J-bob

Reputation: 9106

disabling character escaping in Flask's url_for function

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.

Upvotes: 11

Views: 5050

Answers (1)

Sean Vieira
Sean Vieira

Reputation: 159905

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)

Upvotes: 13

Related Questions