简体   繁体   English

如何在烧瓶restful api中响应unicode字符串?

[英]How to response a unicode string in flask restful api?

I am using flask.ext.rest to build a api. 我正在使用flask.ext.rest来构建一个api。 I want return some chinese string. 我想要返回一些中文字符串。 However, every time I receive "\爱" (This is a string of length 8). 但是,每次我收到"\爱" (这是一个长度为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. get方法应该返回一个Response实例。 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. '\\ u7231'确实是你寻找的角色,问题在于通过你用来显示它的任何设备渲染那个角色。

So your browser page probably needs to include a meta tag to render UTF-8 因此,您的浏览器页面可能需要包含meta标记来呈现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. 另一方面,cURL为你提供了一个快速谷歌,听起来它默认收到unicode char ok所以这只是你用来存储/显示结果的问题...你需要阻止终端或文件系统或程序,或者你正在使用的任何东西,将unicode char转换回它的数字表示。 So if you save it to file you need to ensure that file gets a utf-8 character encoding; 因此,如果将其保存到文件,则需要确保该文件获得utf-8字符编码; if you render it to screen you need ensure your screen is capable and expecting it. 如果你将它渲染到屏幕,你需要确保你的屏幕能够并期待它。

make_response can actually solve the problem. make_response实际上可以解决问题。

My case is slightly different, as I have a dictionary object and it hasn't not been encoded to utf-8 yet . 我的情况略有不同,因为我有一个字典对象, 但尚未编码为utf-8 so I modify the solution from @Xing Shi, in case there are someone else having similar problem as I did. 所以我修改@Xing Shi的解决方案,以防有其他人遇到类似的问题。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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