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.
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.
Most helpful comment
The latest release adds
request.get_data()which should be used instead ofrequest.data, it provides anas_textparameter you can use to get unicode instead of bytes.