繁体   English   中英

Flask-Restful API和JSON问题中的Unicode

[英]Unicode in Flask-Restful API and JSON issue

我遇到了与Flask-Restful API服务器的ajax请求中的unicode相关的奇怪问题。 问题仅出现在一台计算机上,而不是另一台计算机上。

我有一个宁静的课。 您可能会注意到字符字段设置为unicode。

class PostListApi(Resource):
def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument('body', type = unicode, required = True, help = 'No description provided', location = 'json')
        self.reqparse.add_argument('longitude', type = float, required = False, help = 'Unknown address', location = 'json')
        self.reqparse.add_argument('latitude', type = float, required = False, help = 'Unknown address', location = 'json')
        self.reqparse.add_argument('address', type = unicode, required = True, help = 'No address specified', location = 'json')
        self.reqparse.add_argument('scheduled', type = str, required = True, help = 'Not scheduled correctly', location = 'json')
        super(PostListApi, self).__init__()

我的问题是,当我在BODY中发送带拉丁字符的ajax请求时,服务器会回复400错误。

Request URL:
Request Method:POST
Status Code:400 BAD REQUEST
Request Headersview source
Accept:undefined
Accept-Encoding:gzip,deflate,sdch
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
Content-Length:159
**Content-Type:application/json; charset=UTF-8**
Proxy-Authorization:Basic a3lyeWxvLnlhdHNlbmtvOnBhc3N3b3JkMTIzNDU2
Proxy-Connection:keep-alive
User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payloadview parsed
{"body":"this is a test","address":"141 Rue Saint-Martin, 75003 Paris, France","longitude":2.351530499999967,"latitude":48.8614575,"scheduled":"20131017 1000"}

但是当数据采用cyrilic字母表时,服务器会正​​确管理请求。

Request URL:
Request Method:POST
Status Code:500 INTERNAL SERVER ERROR
Request Headersview source
Accept:undefined
Accept-Encoding:gzip,deflate,sdch
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
Content-Length:208
**Content-Type:application/json; charset=UTF-8**
Cookie:
Proxy-Authorization:Basic a3lyeWxvLnlhdHNlbmtvOnBhc3N3b3JkMTIzNDU2
Proxy-Connection:keep-alive
User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payloadview source
{body:Йн незл ножтрюд оффÑндйт вÑш,…}
address: "Йн незл ножтрюд оффÑндйт вÑш"
body: "Йн незл ножтрюд оффÑндйт вÑш"
latitude: 48.8614575
longitude: 2.351530499999967
scheduled: "20131017 1000"
Response Headersview source
Connection:Keep-Alive
Content-Length:51
Content-Type:application/json
Date:Thu, 17 Oct 2013 08:03:41 GMT
Proxy-Connection:Keep-Alive
Server:WSGIServer/0.1 Python/2.7.5

使用jquery的ajax方法完成请求生成

function ajaxRequest(uri, method, data){
    var request = {
                url: uri,
                type: method,
                contentType: "application/json; charset=utf-8",
                accepts: "application/json",
                cache: false,
                dataType: 'json',
                //data: data != null?((method == 'GET') ? $.param(data): utf8_encode(JSON.stringify(data))):null,
                data: data != null?((method == 'GET') ? $.param(data): JSON.stringify(data)):null,
                beforeSend: function (xhr) {},
                error: function(jqXHR) {
                    console.log("ajax error " + jqXHR.status);
                }
            };
    return $.ajax(request);

你以前遇到过类似的问题吗? 怎么解决这个问题? 我想在发送到服务器之前,拉丁字符也必须编码为unicode。 我怎么能强制jquery将所有内容编码为unicode?

提前致谢!

我使用跟随代码,我没有这个问题和输出问题

import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from flask import Flask
from flask.ext.restful import Api
from flask.ext.restful.representations.json import output_json
output_json.func_globals['settings'] = {'ensure_ascii': False, 'encoding': 'utf8'}
app = Flask(__name__)
api = Api(app)
...

暂无
暂无

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

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