简体   繁体   中英

How to response a unicode string in flask restful api?

I am using flask.ext.rest to build a api. I want return some chinese string. However, every time I receive "\爱" (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

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)

'\爱' 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.

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'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM