类型错误:flask中的预期字符串或缓冲区解码json [duplicate]

时间:2022-10-17 13:00:51

This question already has an answer here:

这个问题已经有了答案:

I'm working with a a distributed system where a php app sends a post request to a python flask app.

我正在开发一个分布式系统,php应用程序向python flask应用程序发送post请求。

I have a 2d php array ($data) that looks like:

我有一个2d php数组($data),看起来像:

array(3) { [0]=> array(2) { ["a"]=> 'aaa' ["token"]=> string(55) "146bf00b2cb8709" } [1]=> array(2) { ["a"]=> string(52) "bbb" ["token"]=> string(55) "146bf00b2cb96e74302" } [2]=> array(2) { ["a"]=> string(52) "ccc" ["token"]=> string(55) "146bf00b2cb96e6c422417" } }

following How to Send 2D array through php cURL

下面介绍如何通过php cURL发送2D数组。

I have:

我有:

$json =  json_encode($data);
$ch = curl_init();  

curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false); 
curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);    
$output=curl_exec($ch);

In flask, my code is:

在flask中,我的代码是:

@app.route('/index',methods=['POST'])
def index():

    import json
    r = request # receives request from php
    json = json.loads(r.form)

and I can see that the request is coming through as JSON:

我可以看到请求是JSON格式的:

>>> r.form
Out[12]: ImmutableMultiDict([('[{"a":"aaa","token":"146bf00b2cb96e6c425c2ab3f7daa11c55e4bc6eb5f2d5.46266037"},{"a":"bbb","token":"decdbc1691816cae83392e2a379a2c2555e4bc60df5f86.89400754"},{"a":"ccc","token":"146bf00b2cb96e6c425c2ab3f7daa11c55e4bc6e039320.76477875"}]', u'')])

But I can't seem to get it into a parsable form. I' getting the error above. How can I access this JSON string?

但我似乎不能把它变成可分割的形式。我得到上面的错误。如何访问这个JSON字符串?

1 个解决方案

#1


1  

@app.route('/index',methods=['POST'])
def index():
    json = request.get_json()

#1


1  

@app.route('/index',methods=['POST'])
def index():
    json = request.get_json()