简体   繁体   English

Python请求库发布请求在本地开发服务器上失败?

[英]Python Requests Library post requests failing on local development server?

Ok so I have been looking at the code I have for far too long I know through I number of tests that I must be facing an issue beyond the scope of my knowledge. 好吧,我一直在看我的代码太久了,通过大量的测试,我知道我必须面对超出我所知范围的问题。

In short, I am trying to send data that I have received from an Arduino (connected to my laptop, and communicating via serial port) to a server that is running on my laptop. 简而言之,我试图将我从Arduino(连接到我的笔记本电脑,并通过串行端口进行通信)接收的数据发送到笔记本电脑上运行的服务器。

I am trying to send various pieces of information in a POST requests using the Requests Library as follows: 我正在尝试使用请求库按以下方式在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

This code works. 此代码有效。 I know this because I tested it at http://www.posttestserver.com/ . 我知道这一点是因为我在http://www.posttestserver.com/上对其进行了测试。 All of the data is sent properly. 所有数据均已正确发送。

But I am trying to send it to a server side script that looks like this: 但是我试图将其发送到如下所示的服务器端脚本:

<?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";

?>

However when I run the code, my script spits out: 但是,当我运行代码时,我的脚本会弹出:

<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.>

What could be going wrong? 可能出什么问题了? Thanks for your help! 谢谢你的帮助!

$state = $_POST["state"];

You are sending the data as type application/json , but PHP won't auto de-serialize the string into json for you. 您正在以application/json类型发送数据,但是PHP不会为您自动将字符串反序列化为json Also Python Requests will not autoserialize: 同样,Python请求不会自动序列化:

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

into json. 到json。

What you will want to do is serialize the request for on the client side: 您将要做的是在客户端对请求进行序列化:

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

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

Now on the server side, de-serialize it: 现在在服务器端,将其反序列化:

if ($_SERVER["CONTENT_TYPE"] == "application/json") {
    $postBody = file_get_contents('php://input');
    $data = json_decode($postBody);

    $state = $data["state"];
    //rest of your code...
}

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

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