How to retain special characters in url parameters for flask?

Viewed 1333
http://127.0.0.1:3000/segment?text=PA++

text = request.args.get('text')

What I get is 'PA', not 'PA++'.

How to not lose the plus signs in URL? I want to use urllib.urlencode(text) to encode it somehow, but how to get a handle of the 'text' string? because it comes from the request.args.get() function. By the time it returns the values, the special characters are already chopped off.

EDITED:

@api.route('/segment', methods=['GET'])
def segment():
    text = request.args.get('text')
    seg = str(segmenter.segment(text))
    return seg

I don't have any html page or template. Then in the browser, I can make reqeust:

http://0.0.0.0:5000/segment?text=PA++

But the problem is:

text = request.args.get('text')

the returned 'text' is already reduced to 'PA', no plus sign.

1 Answers

I think what you're trying to achieve needs to be done on the frontend before form submission.

As mentioned you need to hit http://127.0.0.1:3000/segment?text=PA%2B%2B in the browser. So the encoding takes place on the frontend. A standard form should do this automatically, so if you consider this sample app:

from flask import Flask, request
app=Flask(__name__)

template="""
<form action='/segment' method='GET'>
<input name='text' type='text' /> 
<input type='submit' />
</form>
"""

@app.route('/segment')
def index():    
    text = request.args.get('text')

    if text:
        print ('Server got: ', text)
        return f"result was: {text}"
    else:
        return template

If you enter PA++ in the input field, and click the submit button:

  • the resulting URL in the browser is: http://localhost:5000/segment?text=PA%2B%2B
  • the server console prints: Server got: PA++
  • the browser renders: result was: PA++

Similarly if you wanted to do this without a form (which appears to handle the encoding automatically) you could do so in Javascript, for example at your dev tools JS console:

>> encoded = '/segment?text=' + encodeURIComponent('PA++')
"/segment?text=PA%2B%2B"

The Python requests library also does this encoding automatically:

>>> import requests
>>> r=requests.get('http://localhost:5000/segment', params = {'text':'PA++'})
>>> r.url
'http://localhost:5000/segment?text=PA%2B%2B'
>>> r.text
'result was: PA++' 
  • Server also outputs: Server got: PA++

And finally for demonstration purposes, with a space in that string:

>>> r=requests.get('http://localhost:5000/segment', params = {'text':'P A'})
>>> r.url
'http://localhost:5000/segment?text=P+A'
>>> r.text
'result was: P A'
  • Server output: Server got: P A
Related