Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 294
J-bob Avatar asked Dec 04 '14 17:12

J-bob


People also ask

What does flask's url_for () do?

url_for in Flask is used for creating a URL to prevent the overhead of having to change URLs throughout an application (including in templates). Without url_for , if there is a change in the root URL of your app then you have to change it in every page where the link is present.

What is url_for?

The url_for() function generates the URL to a view based on a name and arguments. The name associated with a view is also called the endpoint, and by default it's the same as the name of the view function.


1 Answers

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)
like image 143
Sean Vieira Avatar answered Sep 30 '22 18:09

Sean Vieira