I've been doing experiments using flasks and jsonify. It works. But doesn't support utf-8 chararacters (turkish characters). I'm using a dictionary.
if api_key in key_list:
quotes = {
'ataturk':
['Hayatta En Hakiki Mursit Ilimdir Fendir',
'Birgün benim naciz bedenim'],
'mahatma gandhi':
['Happiness is when what you think, what you'
'say,and what you do are in harmony.']
}
get_quote = quotes[karakter(author.lower(), harfler)]
quote = {
'quotes': random.choice(get_quote),
}
return jsonify(quote)
I've tried encode but it's not working. I got this error in debug mode:
AttributeError: 'dict' object has no attribute 'encode'
How can I solve this problem?
jsonify() is a helper method provided by Flask to properly return JSON data. jsonify() returns a Response object with the application/json mimetype set, whereas json. dumps() simply returns a string of JSON data.
No, returning a dict in Flask will not apply jsonify automatically. In fact, Flask route cannot return dictionary.
You are correct, jsonify does not support UTF-8 characters. It does, however, support Unicode characters perfectly well.
Consider these two programs:
# http server
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/')
def root():
return jsonify({'quote':'Birgün'})
if __name__=='__main__':
app.run(debug=True)
# http client
import requests
import unicodedata
r = requests.get('http://localhost:5000/')
j = r.json()
u = j['quote'][4]
print("%s: %d %x %s\n"%(u, len(u), ord(u), unicodedata.name(u)))
As you can see, the http client fetches the JSON, decodes it, and checks the "ü" in "Birgün".
The result should make it clear that the ü survived the end-to-end trip, from a Python3 string, through JSON and HTTP, and back into a Python3 string.
ü: 1 fc LATIN SMALL LETTER U WITH DIAERESIS
EDIT: Having said all of that, there is a configuration option which will force jsonify()
to behave as you hope:
app.config['JSON_AS_ASCII'] = False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With