无法在 ESP32 上使用 micropython urequests.post 发布数据

无法在 ESP32 上使用 micropython urequests.post 发布数据

我无法让 micropython 正确地将数据发布到 php 脚本...我正在使用 Thonny 和 ESP32,目前它只为 MAMP 实例提供网络连接。

我有以下 Python 代码,我将其用于 ESP32 上的 micropython 并使用 Python 3.10 进行测试。您可能看得出我是编程新手。我使用的最后一种语言是 Forth,大约 35 年前 ;)

创建字典的函数

    # Parameters to be sent
    timeatsense=str(time.localtime())
    # print('timeatsense= ',timeatsense)
    data = {
        'api_key': 'heyplastuny',
        'sensor': 'temphumpres',
        'location': 'office',
        'temperature': round(100*random.random(),2),
        'humidity': round(20*random.random(),2),
        'whenitwas': timeatsense
        }
    return data```


This is the main function that tries to post the dictionary to the script


```import urequests
   import random
   import time

   # URL of the PHP script on the web server
   url = 'http://192.168.4.55:8888/test1.php'


    datapost=getdata()
    p# print(datapost,"\r\n")
    response = urequests.post(url,data=datapost)
    #response=requests.post(url)
    print("response in python is ",response.text,"\r\n")```



and a very simple php script called test1 residing in the htdocs subdirectory of MAMP


```<?php
 //$api_key = $_POST["api_key"];
 if ($_SERVER["REQUEST_METHOD"] == "POST") {
    echo "dumping content of post now <br>";
    var_dump($_POST);
    //;echo "this is the key <br>" . $api_key . "<br>";
}
else {
    echo "Was not a POST request";
}

?>```

If I use micropython the code throws this error

**TypeError: object with buffer protocol required**
I tried using urequests in micropython thus
response = urequests.post(url,data=datapost)

because this page says
https://docs.openmv.io/library/urequests.html/ that I should be able to send that dictionary in the manner I am using.


If I use regular python 3.10 I get the correct answer using the same code which shows the script with the dictionary I sent

```dumping content of post now <br>array(6) {
  ["api_key"]=>
  string(11) "testkey"
  ["sensor"]=>
  string(11) "temphumpres"
  ["location"]=>
  string(6) "office"
  ["temperature"]=>
  string(5) "42.97"
  ["humidity"]=>
  string(5) "18.73"
  ["whenitwas"]=>
  string(24) "Wed Feb 14 22:06:27 2024"
}

 with length  304 ```




If instead I use response = urequests.post(url,json=datapost)
I get 
```response in python is  dumping content of post now <br>array(0) {
}```


The notion of using json was from some post I have forgotten, but the point is that it shows that I am at least getting through to the php script over the network.

Any indication as to where I am going wrong would be most appreciated. I have spent a long time looking at various posts to no avail.
Thanks, especially if you can solve this..


相关内容