Flask: Request.data should be unicode

Created on 18 Apr 2013  路  2Comments  路  Source: pallets/flask

Why isn't request.data of type unicode? The following test application reveals that the type is str.

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

@app.route('/', methods=['POST'])
def index():
    return str(type(request.data))

if __name__ == '__main__':
    app.run(debug=True)

This is an issue if, for example, I have a Flask application that receives a JSON string as request data, then attempts to insert that data into a database that requires a unicode value.

Most helpful comment

The latest release adds request.get_data() which should be used instead of request.data, it provides an as_text parameter you can use to get unicode instead of bytes.

All 2 comments

The request data is the unparsed, undecoded bytes that came as request body. If you want unicode you can decode it yourself:

request_text = request.data.decode('utf-8')

And if you happen to need the parsed JSON content, flask provides a convenience attribute, request.json. See the documentation on request data for more information.

The latest release adds request.get_data() which should be used instead of request.data, it provides an as_text parameter you can use to get unicode instead of bytes.

Was this page helpful?
0 / 5 - 0 ratings