7

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.

Paco
  • 4,520
  • 3
  • 29
  • 53
Tampa
  • 75,446
  • 119
  • 278
  • 425

1 Answers1

5

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)
Sevak Avakians
  • 883
  • 8
  • 13
  • 4
    In Python 3, `unquote_plus` can be found in `urllib.parse` instead of `urllib`. – Alex Peters Jun 16 '19 at 06:22
  • 1
    Flask automatically decodes the form data. It's not necessary to decode/unquote_plus that within the framework. – Rick Aug 13 '19 at 04:56
  • @Rick, the question was regarding decoding URL strings in a template, not in the form data. This answer can be used to provide that template with the properly formatted URL string. – Sevak Avakians Aug 14 '19 at 15:55