Timezone: Europe/London

.

AboutContactMicropythonESP32Links
Moonlight Systems

Hassle free web communication with urequests.py

December 25

In Micropython, I use the uRequests module extensively to send GET requests to retrieve or action PHP scripts on my webserver. I use this is mostly to send and receive data from a web based database, but the possibilities go much further than that.
The uRequests module handles all of the coding involved in setting up sockets and protocols, handshaking and communicating with servers.
You just install your PHP script on the server, and access it by starting an internet connection in your python code, and sending one request to the server such as "result = urequests.get(url, webpage.php)".

Here is some sample code for uploading some data from a text log to an online database.
Say we want to log battery voltage, temperature, pressure and humidity from sensors every hour along with a timestamp.
As I am running my units on batteries, I don't want to expend the power to use wifi every hour, so I save these in a text file and upload periodically, say twice a day.
Write your code to take these readings and save to a textfile ready formatted to be sent as a PHP query string. This is basically a string with key/value pairs joined by the ampersand character.
You may end up with something like this

voltage=4.4&temp=18.45&humidity=74.87&pressure=1032×tamp=10-12-2025 09:45:00
voltage=4.4&temp=18.45&humidity=74.87&pressure=1032×tamp=10-12-2025 10:45:00
voltage=4.3&temp=18.45&humidity=74.87&pressure=1032×tamp=10-12-2025 11:45:00
voltage=4.3&temp=18.45&humidity=74.87&pressure=1032×tamp=10-12-2025 12:45:00
voltage=4.2&temp=18.45&humidity=74.87&pressure=1032×tamp=10-12-2025 13:45:00

A simple PHP script to accept this data. This is for demonstration only, and contains no validation or error checking.


In uPython the code to upload the data would go something like this.
You need to import the urequests module into your code. "import urequests"

Using requests GET for this type of scenario is very straightforward but does have its drawbacks, a major one being security.
GET is not secure at all, as everything is in plain text. A more secure way of sending data is using requests.POST()
but there are caveats which I will go into in the next article.

Using requests to POST data

Links

IDE editors for programming ESP boards.
Micropython editors

Micropython functionality and libraries.
Micropython.org

Find the uPython firmware for your board.
uPython firmware for development boards.

ESP32 uPython modules and function examples.
Quick reference for the ESP32

Finding the MAC address

Scanning and connecting to multiple SSIDs

Using an SD card reader breakout board

ESP32 Real Time Clock

The Deepsleep function

Storing variables in the RTC

RTC Tuning

OTA Updating running software without interuption

Hassle free web communication with urequests.py.

A very basic problem...

Future articles

Communication between ESPs