Python 请求库 post 请求在本地开发服务器上失败?
Python Requests Library post requests failing on local development server?
好的,所以我查看我的代码已经太久了,我通过大量测试知道我必须面对超出我知识范围的问题。
简而言之,我正在尝试将从 Arduino(连接到我的笔记本电脑,并通过串口通信)收到的数据发送到我笔记本电脑上 运行ning 的服务器。
我正在尝试使用请求库在 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.>
可能出了什么问题?感谢您的帮助!
$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...
}
好的,所以我查看我的代码已经太久了,我通过大量测试知道我必须面对超出我知识范围的问题。
简而言之,我正在尝试将从 Arduino(连接到我的笔记本电脑,并通过串口通信)收到的数据发送到我笔记本电脑上 运行ning 的服务器。
我正在尝试使用请求库在 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.>
可能出了什么问题?感谢您的帮助!
$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...
}