Reputation: 15
I am using Flask to building a REST API, but when I pass query parameters with Chinese Character, I got garbled characters instead of Chinese
from flask import Blueprint
from flask_restful import Resource, Api
class Keyword(Resource):
def post(self, keyword):
return {"keyword": "keyword"}
keyword_api = Blueprint('resourses.keyword', __name__)
api = Api(keyword_api)
api.add_resource(
Keyword,
'/keyword/<string:keyword>',
endpoint='keyword'
)
POST http://localhost:5000/keyword/價錢
I expected the output of {"keyword": "價錢"}, but the actual output is {"keyword": "è²´é\u0081\u008e"}
Update: Right now I added this to the code, it returns {"keyword": "價錢"} correctly
keyword = keyword.encode('iso-8859-1').decode('utf8')
Upvotes: 1
Views: 1656
Reputation: 9
The type is 'utf-8'
but decoded by'iSO-8859-1'
, so there are garbled characters. The Bytes
data was decoded into Str
by 'iso-8859-1'
. When you encoded it by 'iso-8859-1'
, it changed back to Bytes
data again, then decoded it by utf-8
and the output was right. It's the change between different encoding/decoding types. You may set the decoding type to be utf-8
if you find the corresponding parameters.
Upvotes: 0
Reputation: 1806
The code seems to be functioning correctly. I have taken the liberty of modifying it a bit and make it into a working example. Important thing to notice is that b'{"keyword": "\u50f9\u9322"}' object type is bytes denoted by b prefix. If you serialize this data from json to python native string, you will find it is valid 價錢 encoded.
from flask import Blueprint, Flask
from flask_restful import Resource, Api
from werkzeug.local import LocalProxy
from logging import DEBUG
app = Flask(__name__)
app.logger.setLevel(DEBUG)
logger = LocalProxy(lambda: app.logger)
class Keyword(Resource):
def post(self, keyword):
logger.info("Keyword: {}".format(type(keyword)))
return {"keyword": keyword}
keyword_api = Blueprint('resourses.keyword', __name__)
api = Api(keyword_api)
api.add_resource(
Keyword,
'/keyword/<string:keyword>',
endpoint='keyword'
)
app.register_blueprint(keyword_api)
Upvotes: 1