【问题标题】:Python Requests Library post requests failing on local development server?Python请求库发布请求在本地开发服务器上失败?
【发布时间】:2015-07-28 01:15:20
【问题描述】:

好的,所以我一直在研究我拥有的代码太久了,我通过许多测试知道我必须面临超出我知识范围的问题。

简而言之,我正在尝试将从 Arduino(连接到我的笔记本电脑,并通过串行端口进行通信)接收到的数据发送到在我的笔记本电脑上运行的服务器。

我正在尝试使用请求库在 POST 请求中发送各种信息,如下所示:

import requests
import json

url = 'http://<usernames computer>.local/final/'
headers = {'Content-type': 'application/json'}
data = [
    ('state','true'),
    ('humidity', 45),
    ('temperature',76)
]

r = requests.post(url, data, headers = headers)

print r.text

此代码有效。我知道这一点,因为我在http://www.posttestserver.com/ 测试过它。所有数据均已正确发送。

但我正在尝试将其发送到如下所示的服务器端脚本:

<?php   
$state = $_POST["state"];

$myfile = fopen("./data/current.json", "w") or die("Unable to open file!");
$txt = "$state";

fwrite($myfile, $txt);
fclose($myfile);

echo "\nThe current state is:\n $state\n";

?>

但是,当我运行代码时,我的脚本会吐出:

<br />
<b>Notice</b>:  Undefined index: state in
<b>/Applications/XAMPP/xamppfiles/htdocs/final/index.php</b> on line   
<b>2</b><br />

The current state is:
<This is where something should come back, but does not.>

可能出了什么问题?感谢您的帮助!

【问题讨论】:

    标签: php python post xampp


    【解决方案1】:
    $state = $_POST["state"];
    

    您以application/json 类型发送数据,但PHP 不会为您自动将字符串反序列化为json。 Python 请求也不会自动序列化:

    [
    ('state','true'),
    ('humidity', 45),
    ('temperature',76)
    ]
    

    转成 json。

    您要做的是在客户端序列化请求:

    data = [
        ('state','true'),
        ('humidity', 45),
        ('temperature',76)
    ]
    
    r = requests.post(url, json=data, headers=headers)
    

    现在在服务器端,反序列化它:

    if ($_SERVER["CONTENT_TYPE"] == "application/json") {
        $postBody = file_get_contents('php://input');
        $data = json_decode($postBody);
    
        $state = $data["state"];
        //rest of your code...
    }
    

    【讨论】:

    • 这太完美了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-25
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多