In the MicroPython ecosystem, the uasyncio
library provides the asynchronous I/O framework for developing concurrent applications, but it lacks a native asynchronous HTTP client that can make non-blocking HTTP/HTTPS requests.
Here, I'm sharing my attempt at implementing an HTTP client built specifically for MicroPython that leverages uasyncio
to enable non-blocking requests.
-
Asynchronous and Concurrent:
AsyncHttpClient
is built uponuasyncio
, the asyncio library for MicroPython, allowing multiple HTTP/HTTPS requests to be made concurrently without blocking the execution of other coroutines. -
HTTP/HTTPS Support:
AsyncHttpClient
can handle both HTTP and HTTPS requests, providing flexibility in communicating with different servers. -
Timeout and Retries: It supports custom settings for connection and response timeouts, as well as the number of retries in case of request failure.
-
Robust Error Handling:
AsyncHttpClient
is designed to robustly handle potential errors and exceptions that might occur during network programming. -
User Agent: It includes a User-Agent in the request headers to identify the client.
-
JSON Parsing:
AsyncHttpClient
automatically parses JSON responses if the content type isapplication/json
.
The GET
method can be called asynchronously with a URL. The method returns the body of the response as a string or a dictionary if the response is in JSON format.
This is a basic example where we simply fetch a web page:
# Import the necessary modules
import asyncio
from async_http_client import AsyncHttpClient
# Define an asynchronous function to fetch a web page
async def fetch_page():
# Create an AsyncHttpClient instance
client = AsyncHttpClient()
# Use the client to send a GET request to a web page
response = await client.get('https://example.com')
# Print the response
print(response)
# Run the fetch_page function
asyncio.run(fetch_page())
This example shows a more robust usage where we handle exceptions:
# Import the necessary modules
import asyncio
from async_http_client import AsyncHttpClient
# Define an asynchronous function to fetch a web page
async def fetch_page():
# Create an AsyncHttpClient instance with custom timeout and retries
client = AsyncHttpClient(timeout=10, retries=5)
# Use the client to send a GET request to a web page
try:
response = await client.get('https://example.com')
print(response)
except Exception as e:
print(f'Failed to fetch page: {e}')
# Run the fetch_page function
asyncio.run(fetch_page())
This is a realistic example where we use the client to fetch weather data and update a shared state:
# Import the necessary modules
import asyncio
from async_http_client import AsyncHttpClient
# Define a global variable to hold the current temperature
current_temp = None
# Define an asynchronous function to fetch the weather
async def fetch_weather():
# Create an AsyncHttpClient instance
client = AsyncHttpClient()
# Fetch the weather data every 10 minutes
while True:
try:
# Send a GET request to the weather API
response = await client.get('https://api.weatherapi.com/v1/current.json?key=YOUR_KEY&q=YOUR_LOCATION')
# Update the current temperature
global current_temp
current_temp = response['current']['temp_c']
except Exception as e:
print(f'Failed to fetch weather: {e}')
# Wait for 10 minutes before fetching the weather again
await asyncio.sleep(600)
# Define an asynchronous function to display the current temperature
async def display_temperature():
while True:
# Print the current temperature
print(current_temp)
# Wait for 1 second before updating the display
await asyncio.sleep(1)
# Run the fetch_weather and display_temperature functions concurrently
asyncio.run(asyncio.gather(fetch_weather(), display_temperature()))
In this example, the fetch_weather
function sends a GET request to a weather API every 10 minutes and updates the current_temp
global variable. The display_temperature
function displays the current temperature every second. Both functions run concurrently, so the display is updated regularly even while the weather data is being fetched. This is an example of how you might use the AsyncHttpClient
class to fetch data from an API and update a shared state in a real-world application.
- Initial implementation
- Introduce
get(url)
method - Untested