Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decode a url string in a flask template

I am using flask.

In my template I used this to encode a string.

encodeURIComponent(mytag)

Now I want to decode in another template.
Where is what the string looks like.

%26lt%3B!--Afff%20Tracking%20Tag--%26gt%3B%0A%26lt%3Bimg%20src%3D%22http%3A%2F%2Fcm.g.doubleclick.net%2Fpixel%3F%0Agggg_nid%3Dhff%26gggg_cm%26avid%3David3966173574%26campaign_id%3Dundefined%22%20%2F%26gt%3B

In the template how do I decode the string?

{% for crid, object in tag_handler.iteritems() %}
    <script>var x = decodeURI("{{object['tag_display']}}"); alert(x);</script>
        <div id="tagBox" style="display: block;width: 700px">
            <pre class="prettyprint">
                <code class="language-html">    
                    {{object['tag_display']}}
                </code>
            </pre>
       </div>

{% endfor %}

I am using google pretty to display the string.

like image 488
Tampa Avatar asked Sep 19 '12 14:09

Tampa


People also ask

How do I decode a string with URL?

In JavaScript, PHP, and ASP there are functions that can be used to URL encode a string. PHP has the rawurlencode() function, and ASP has the Server.URLEncode() function. In JavaScript you can use the encodeURIComponent() function. Click the "URL Encode" button to see how the JavaScript function encodes the text.

Does flask automatically decode URL?

No, Flask is usually handling percent encoding exactly right. Parameters in a URL are percent encoded, and these are decoded for you when the WSGI environment is set up. Flask then passes this on to your route when matching. You do not need to decode the parameter value again, remove your urllib.

How do I decode a URL in Python?

In Python 3+, You can URL decode any string using the unquote() function provided by urllib. parse package. The unquote() function uses UTF-8 encoding by default.

What does %2f mean in a URL?

URL encoding converts characters into a format that can be transmitted over the Internet. - w3Schools. So, "/" is actually a seperator, but "%2f" becomes an ordinary character that simply represents "/" character in element of your url.


1 Answers

You can use Python's urllib. There are a couple of options, unquote and unquote_plus. See https://unspecified.wordpress.com/2008/05/24/uri-encoding/ for explanation. In brief, "Choose unquote_plus if your URLs use ‘+’ for spaces, and remember that HTML forms do this automatically."

from urllib import unquote_plus
@app.route('/foo', methods=['POST'])
def foo():
    mytag = request.form['params']
    print unquote_plus(mytag)
like image 95
SevakPrime Avatar answered Sep 30 '22 17:09

SevakPrime