Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在flask restful api中响应unicode字符串?_Python_Utf 8_Flask Restful - Fatal编程技术网

Python 如何在flask restful api中响应unicode字符串?

Python 如何在flask restful api中响应unicode字符串?,python,utf-8,flask-restful,Python,Utf 8,Flask Restful,我正在使用flask.ext.rest构建api。我想要一些中文字符串。但是,每次我收到“\u7231”(这是一个长度为8的字符串)。我应该如何接收爱 from flask import Flask from flask.ext.restful import reqparse, abort, Api, Resource class E2C(Resource): # English to Chinglish def get(self): chinese = u'爱'

我正在使用flask.ext.rest构建api。我想要一些中文字符串。但是,每次我收到
“\u7231”
(这是一个长度为8的字符串)。我应该如何接收

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

“\u7231”确实是您要查找的角色,问题在于您使用的任何设备都无法显示该角色

因此,您的浏览器页面可能需要包含一个
meta
标记来呈现UTF-8

<head>
<meta charset="UTF-8">
</head>


另一方面,cURL为您提供了一个快速的google,它听起来像默认情况下接收unicode字符ok,所以这只是一个您使用什么来存储/显示结果的问题。。。您需要防止终端、文件系统或程序,或者您正在使用的任何东西,将unicode字符转换回其数字表示形式。所以,如果您将其保存到文件中,您需要确保该文件获得utf-8字符编码;如果将其呈现到屏幕上,则需要确保屏幕能够正常显示。

get
方法应返回一个响应实例。看这里

代码应为:

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)

做出响应实际上可以解决问题

我的情况稍有不同,因为我有一个字典对象,它还没有编码到utf-8。所以我修改了@Xing Shi的解决方案,以防有其他人和我有类似的问题

def get(self):
     return make_response(
              dumps({"similar": "爱“, "similar_norm": ”this-thing"},
                  ensure_ascii=False).decode('utf-8'))

通过
receive
您是在谈论浏览器中的演示吗?@JohnMee,是的。通过
receive
,我的意思是从浏览器和命令行(
curl http:…
)接收。无论如何,我只能得到8长度的字符串,而不是1长度的字符串你好,我正在做一个像你这样的小项目,这个问题现在怎么样?