requests_advanced_ethernet.py
1 import board 2 import busio 3 from digitalio import DigitalInOut 4 from adafruit_wiznet5k.adafruit_wiznet5k import WIZNET5K 5 import adafruit_wiznet5k.adafruit_wiznet5k_socket as socket 6 import adafruit_requests as requests 7 8 cs = DigitalInOut(board.D10) 9 spi_bus = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) 10 11 # Initialize ethernet interface with DHCP 12 eth = WIZNET5K(spi_bus, cs) 13 14 # Initialize a requests object with a socket and ethernet interface 15 requests.set_socket(socket, eth) 16 17 JSON_GET_URL = "http://httpbin.org/get" 18 19 attempts = 3 # Number of attempts to retry each request 20 failure_count = 0 21 response = None 22 23 # Define a custom header as a dict. 24 headers = {"user-agent": "blinka/1.0.0"} 25 26 print("Fetching JSON data from %s..." % JSON_GET_URL) 27 while not response: 28 try: 29 response = requests.get(JSON_GET_URL, headers=headers) 30 failure_count = 0 31 except AssertionError as error: 32 print("Request failed, retrying...\n", error) 33 failure_count += 1 34 if failure_count >= attempts: 35 raise AssertionError( 36 "Failed to resolve hostname, \ 37 please check your router's DNS configuration." 38 ) from error 39 continue 40 print("-" * 60) 41 42 json_data = response.json() 43 headers = json_data["headers"] 44 print("Response's Custom User-Agent Header: {0}".format(headers["User-Agent"])) 45 print("-" * 60) 46 47 # Read Response's HTTP status code 48 print("Response HTTP Status Code: ", response.status_code) 49 print("-" * 60) 50 51 # Read Response, as raw bytes instead of pretty text 52 print("Raw Response: ", response.content) 53 54 # Close, delete and collect the response data 55 response.close()