4

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
3
  • by receive are you talking about presentation in a browser? Commented May 27, 2014 at 23:13
  • @JohnMee, yes. By receive, I mean from both browser and command line (curl http:...). In either way, I can only get the 8 length string instead of 1 length string Commented May 27, 2014 at 23:26
  • hello, I am doing a little project like yours, how is this issue now? Commented Aug 1, 2015 at 2:49

3 Answers 3

3

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.