Reputation: 2230
I am using flask.ext.rest to build a api. I want return some chinese string. However, every time I receive "\u7231"
(This is a string of length 8). What should I do to receive 爱
?
from flask import Flask
from flask.ext.restful import reqparse, abort, Api, Resource
class E2C(Resource): # English to Chinglish
def get(self):
chinese = u'爱'
type(chinese) # unicode
return chinese
Upvotes: 4
Views: 7906
Reputation: 5139
make_response can actually solve the problem.
My case is slightly different, as I have a dictionary object and it hasn't not been encoded to utf-8 yet. so I modify the solution from @Xing Shi, in case there are someone else having similar problem as I did.
def get(self):
return make_response(
dumps({"similar": "爱“, "similar_norm": ”this-thing"},
ensure_ascii=False).decode('utf-8'))
Upvotes: 0
Reputation: 2230
The get
method should return a Response instance. see docs here.
The code should be:
from flask import Flask, make_response
from flask.ext.restful import reqparse, abort, Api, Resource
class E2C(Resource): # English to Chinglish
def get(self):
chinese = u'爱'
type(chinese) # unicode
return make_response(chinese)
Upvotes: 3
Reputation: 52243
'\u7231' is indeed the character you seek, the problem is with the rendering of that character by whatever device you're using to display it.
So your browser page probably needs to include a meta
tag to render UTF-8
<head>
<meta charset="UTF-8">
</head>
cURL, on the other hand, given a quick google for you, it sounds like it receives the unicode char ok by default so it's only a question of what you're using to store/display the results... you need to prevent the terminal or file system or program, or whatever you're using, from converting that unicode char back into it's numerical representation. So if you save it to file you need to ensure that file gets a utf-8 character encoding; if you render it to screen you need ensure your screen is capable and expecting it.
Upvotes: 1