requests_advanced.py
1 import board 2 import busio 3 from digitalio import DigitalInOut 4 import adafruit_esp32spi.adafruit_esp32spi_socket as socket 5 from adafruit_esp32spi import adafruit_esp32spi 6 import adafruit_requests as requests 7 8 # Add a secrets.py to your filesystem that has a dictionary called secrets with "ssid" and 9 # "password" keys with your WiFi credentials. DO NOT share that file or commit it into Git or other 10 # source control. 11 # pylint: disable=no-name-in-module,wrong-import-order 12 try: 13 from secrets import secrets 14 except ImportError: 15 print("WiFi secrets are kept in secrets.py, please add them there!") 16 raise 17 18 # If you are using a board with pre-defined ESP32 Pins: 19 esp32_cs = DigitalInOut(board.ESP_CS) 20 esp32_ready = DigitalInOut(board.ESP_BUSY) 21 esp32_reset = DigitalInOut(board.ESP_RESET) 22 23 # If you have an externally connected ESP32: 24 # esp32_cs = DigitalInOut(board.D9) 25 # esp32_ready = DigitalInOut(board.D10) 26 # esp32_reset = DigitalInOut(board.D5) 27 28 spi = busio.SPI(board.SCK, board.MOSI, board.MISO) 29 esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) 30 31 print("Connecting to AP...") 32 while not esp.is_connected: 33 try: 34 esp.connect_AP(secrets["ssid"], secrets["password"]) 35 except RuntimeError as e: 36 print("could not connect to AP, retrying: ", e) 37 continue 38 print("Connected to", str(esp.ssid, "utf-8"), "\tRSSI:", esp.rssi) 39 40 # Initialize a requests object with a socket and esp32spi interface 41 socket.set_interface(esp) 42 requests.set_socket(socket) 43 44 JSON_GET_URL = "http://httpbin.org/get" 45 46 # Define a custom header as a dict. 47 headers = {"user-agent": "blinka/1.0.0"} 48 49 print("Fetching JSON data from %s..." % JSON_GET_URL) 50 response = requests.get(JSON_GET_URL, headers=headers) 51 print("-" * 60) 52 53 json_data = response.json() 54 headers = json_data["headers"] 55 print("Response's Custom User-Agent Header: {0}".format(headers["User-Agent"])) 56 print("-" * 60) 57 58 # Read Response's HTTP status code 59 print("Response HTTP Status Code: ", response.status_code) 60 print("-" * 60) 61 62 # Read Response, as raw bytes instead of pretty text 63 print("Raw Response: ", response.content) 64 65 # Close, delete and collect the response data 66 response.close()