簡體   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