def test_second_send_fails(): mocket.getaddrinfo.return_value = ((None, None, None, None, (IP, 80)), ) sock = mocket.Mocket(HEADERS + ENCODED) sock2 = mocket.Mocket(HEADERS + ENCODED) mocket.socket.call_count = 0 # Reset call count mocket.socket.side_effect = [sock, sock2] adafruit_requests.set_socket(mocket, mocket.interface) response = adafruit_requests.get("http://" + HOST + "/testwifi/index.html") sock.send.assert_has_calls([ mock.call(b"testwifi/index.html"), ]) sock.send.assert_has_calls([ mock.call(b"Host: "), mock.call(HOST.encode("utf-8")), mock.call(b"\r\n"), ]) assert response.text == str(ENCODED, "utf-8") sock.fail_next_send = True adafruit_requests.get("http://" + HOST + "/get2") sock.connect.assert_called_once_with((IP, 80)) sock2.connect.assert_called_once_with((IP, 80)) # Make sure that the socket is closed after send fails. sock.close.assert_called_once() assert sock2.close.call_count == 0 assert mocket.socket.call_count == 2
def test_second_tls_send_fails(): mocket.getaddrinfo.return_value = ((None, None, None, None, (ip, 80)), ) sock = mocket.Mocket(headers + encoded) sock2 = mocket.Mocket(headers + encoded) mocket.socket.call_count = 0 # Reset call count mocket.socket.side_effect = [sock, sock2] adafruit_requests.set_socket(mocket, mocket.interface) r = adafruit_requests.get("https://" + host + "/testwifi/index.html") sock.send.assert_has_calls([ mock.call(b"testwifi/index.html"), ]) sock.send.assert_has_calls([ mock.call(b"Host: "), mock.call(host.encode("utf-8")), mock.call(b"\r\n"), ]) assert r.text == str(encoded, "utf-8") sock.fail_next_send = True adafruit_requests.get("https://" + host + "/get2") sock.connect.assert_called_once_with((host, 443), mocket.interface.TLS_MODE) sock2.connect.assert_called_once_with((host, 443), mocket.interface.TLS_MODE) # Make sure that the socket is closed after send fails. sock.close.assert_called_once() assert sock2.close.call_count == 0 assert mocket.socket.call_count == 2
def SendData(self): global temp global humidity global air global motion global sound try: from secrets import secrets except ImportError: print("All secret keys are kept in secrets.py, please add them there!") raise # Initialize UART connection to the ESP8266 WiFi Module. RX = board.GP17 TX = board.GP16 uart = busio.UART( TX, RX, receiver_buffer_size=2048 ) # Use large buffer as we're not using hardware flow control. esp = adafruit_espatcontrol.ESP_ATcontrol(uart, 115200, debug=False) requests.set_socket(socket, esp) print("Resetting ESP module") esp.soft_reset() # Connect to WiFi print("Connecting to WiFi...") esp.connect(secrets) print("Connected!") yield while True: # Update the blynk datastream using HTTP GET requests requests.get("https://blynk.cloud/external/api/update?token=" + secrets["blynk_auth_token"] + "&v0=" + str(temp)) yield [pyRTOS.timeout(0.5)] # Let other tasks run requests.get("https://blynk.cloud/external/api/update?token=" + secrets["blynk_auth_token"] + "&v1=" + str(humidity)) yield [pyRTOS.timeout(0.5)] # Let other tasks run requests.get("https://blynk.cloud/external/api/update?token=" + secrets["blynk_auth_token"] + "&v2=" + str(air)) yield [pyRTOS.timeout(0.5)] # Let other tasks run requests.get("https://blynk.cloud/external/api/update?token=" + secrets["blynk_auth_token"] + "&v3=" + str(motion)) yield [pyRTOS.timeout(0.5)] # Let other tasks run requests.get("https://blynk.cloud/external/api/update?token=" + secrets["blynk_auth_token"] + "&v4=" + str(sound)) yield [pyRTOS.timeout(0.5)] # Let other tasks run # Reset the global variables if motion: motion = 0 if sound: sound = 0 yield [pyRTOS.timeout(0.5)] # Delay in seconds (Other task can run)
def _run_get_request_with_retry(self, url, headers): retry = 0 response = None while True: gc.collect() try: self._logger.debug("Trying to send...") response = requests.get(url, headers=headers) self._logger.debug("Sent!") break except RuntimeError as runtime_error: self._logger.info( "Could not send data, retrying after 0.5 seconds: " + str(runtime_error) ) retry = retry + 1 if retry >= 10: self._logger.error("Failed to send data") raise time.sleep(0.5) continue gc.collect() return response
def test_first_read_fails(): mocket.getaddrinfo.return_value = ((None, None, None, None, (ip, 80)), ) sock = mocket.Mocket(b"") sock2 = mocket.Mocket(headers + encoded) mocket.socket.call_count = 0 # Reset call count mocket.socket.side_effect = [sock, sock2] adafruit_requests.set_socket(mocket, mocket.interface) r = adafruit_requests.get("http://" + host + "/testwifi/index.html") sock.send.assert_has_calls([ mock.call(b"testwifi/index.html"), ]) sock.send.assert_has_calls([ mock.call(b"Host: "), mock.call(host.encode("utf-8")), mock.call(b"\r\n"), ]) sock2.send.assert_has_calls([ mock.call(b"Host: "), mock.call(host.encode("utf-8")), mock.call(b"\r\n"), ]) sock.connect.assert_called_once_with((ip, 80)) sock2.connect.assert_called_once_with((ip, 80)) # Make sure that the socket is closed after the first receive fails. sock.close.assert_called_once() assert mocket.socket.call_count == 2
def get_calendar_events(calendar_id, max_events, time_min): """Returns events on a specified calendar. Response is a list of events ordered by their start date/time in ascending order. """ time_max = get_current_time(time_max=True) print("Fetching calendar events from {0} to {1}".format( time_min, time_max)) headers = { "Authorization": "Bearer " + google_auth.access_token, "Accept": "application/json", "Content-Length": "0", } url = ("https://www.googleapis.com/calendar/v3/calendars/{0}" "/events?maxResults={1}&timeMin={2}&timeMax={3}&orderBy=startTime" "&singleEvents=true".format(calendar_id, max_events, time_min, time_max)) resp = requests.get(url, headers=headers) resp_json = resp.json() if "error" in resp_json: raise RuntimeError("Error:", resp_json) resp.close() # parse the 'items' array so we can iterate over it easier items = [] resp_items = resp_json["items"] if not resp_items: print("No events scheduled for today!") for event in range(0, len(resp_items)): items.append(resp_items[event]) return items
def get_local_time(self, location=None): # pylint: disable=line-too-long """Fetch and "set" the local time of this microcontroller to the local time at the location, using an internet time API. :param str location: Your city and country, e.g. ``"New York, US"``. """ # pylint: enable=line-too-long self.connect() api_url = None try: aio_username = secrets["aio_username"] aio_key = secrets["aio_key"] except KeyError: raise KeyError( "\n\nOur time service requires a login/password to rate-limit. Please register for a free adafruit.io account and place the user/key in your secrets file under 'aio_username' and 'aio_key'" # pylint: disable=line-too-long ) from KeyError if location is None: location = secrets.get("timezone") if location: print("Getting time for timezone", location) api_url = (TIME_SERVICE + "&tz=%s") % (aio_username, aio_key, location) else: # we'll try to figure it out from the IP address print("Getting time from IP address") api_url = TIME_SERVICE % (aio_username, aio_key) api_url += TIME_SERVICE_STRFTIME try: response = requests.get(api_url, timeout=10) if response.status_code != 200: error_message = ( "Error connection to Adafruit IO. The response was: " + response.text ) raise ValueError(error_message) if self._debug: print("Time request: ", api_url) print("Time reply: ", response.text) times = response.text.split(" ") the_date = times[0] the_time = times[1] year_day = int(times[2]) week_day = int(times[3]) is_dst = None # no way to know yet except KeyError: raise KeyError( "Was unable to lookup the time, try setting secrets['timezone'] according to http://worldtimeapi.org/timezones" # pylint: disable=line-too-long ) from KeyError year, month, mday = [int(x) for x in the_date.split("-")] the_time = the_time.split(".")[0] hours, minutes, seconds = [int(x) for x in the_time.split(":")] now = time.struct_time( (year, month, mday, hours, minutes, seconds, week_day, year_day, is_dst) ) rtc.RTC().datetime = now # now clean up response.close() response = None gc.collect()
def get_url(): URL = "http://wifitest.adafruit.com/testwifi/index.html" r = requests.get(URL) print("Status:", r.status_code) print("Content type:", r.headers['content-type']) print("Content size:", r.headers['content-length']) print("Encoding:", r.encoding) print("Text:", r.text)
def get_forecast(location): url = get_data_source_url(api="onecall", location=location) try: r = requests.get(url) raw_data = r.json() r.close() return raw_data["daily"], raw_data["current"]["dt"], raw_data[ "timezone_offset"] except: return None
def ha_request(self, method, path, data = ''): headers = { 'Authorization': 'Bearer ' + self.access_token, 'Content-Type': 'application/json', } if method == "POST": response = requests.post(self.url + path, data = data, headers = headers) elif method == "GET": response = requests.get(self.url + path, headers = headers) return response
def update_weather(): print("updating weather...") response = requests.get(WEATHER_URL) weather = json.loads(response.text) weather_main = weather['main'] temp = weather_main['temp'] pressure = weather_main['pressure'] humidity = weather_main['humidity'] desc = weather['weather'][0]['description'] response.close() return (temp, pressure, humidity, desc)
def Get(thing, property): urlValue = urlBase + 'Things/' + thing + '/Properties/' + property try: response=requests.get(urlValue, headers=headers) value = json.loads(response.text) result = int(value["rows"][0][property]) response.close() except Exception as e: print(e) result=e return result
def get_latlon(): url = get_data_source_url(api="forecast5", location=secrets["openweather_location"]) try: r = requests.get(url) raw_data = r.json() r.close() return raw_data["city"]["coord"]["lat"], raw_data["city"]["coord"][ "lon"] except: return None
def test_get_json(): mocket.getaddrinfo.return_value = ((None, None, None, None, (ip, 80)), ) sock = mocket.Mocket(headers + encoded) mocket.socket.return_value = sock adafruit_requests.set_socket(mocket, mocket.interface) r = adafruit_requests.get("http://" + host + "/get") sock.connect.assert_called_once_with((ip, 80)) assert r.json() == response r.close()
def test_get_json(): mocket.getaddrinfo.return_value = ((None, None, None, None, (IP, 80)), ) sock = mocket.Mocket(HEADERS + ENCODED) mocket.socket.return_value = sock adafruit_requests.set_socket(mocket, mocket.interface) response = adafruit_requests.get("http://" + HOST + "/get") sock.connect.assert_called_once_with((IP, 80)) assert response.json() == RESPONSE response.close()
def datadog_get_metrics_totaled(current_time, query, metric_name, trailing_string, time_range, high_threshold): ''' Fetches a given datadog metric query, and totals all the datapoints in the given time range ''' FROM_TIME = int(current_time) - time_range JSON_URL = "https://api.datadoghq.com/api/v1/query?api_key=" + DD_CLIENT_API_KEY + "&application_key=" + DD_CLIENT_APP_KEY + "&from=" + str( FROM_TIME) + "&to=" + str(current_time) + "&query=" + query print('Using time range in DD request:', FROM_TIME, "to", current_time) print('Running query:', query) try: r = requests.get(JSON_URL) print("-" * 60) json_resp = r.json() # print(json_resp) # Raw JSON totalled_data_points = 0 for i in json_resp["series"][0]["pointlist"]: # print(i[1]) totalled_data_points = totalled_data_points + i[1] # print(json_resp["series"][0]["pointlist"]) # last_data_point = json_resp["series"][0]["pointlist"][-1] # Get latest value in time series # print(last_data_point[1]) print(totalled_data_points) # Update display with result title_text.text = metric_name # Set colour to red if value over threshold if totalled_data_points > high_threshold: print('Value over threshold!') data_display_label.color = red else: data_display_label.color = white data_display_label.text = "" + str(totalled_data_points).split( ".")[0] + trailing_string # Check we're not smashing the API rate limit if int(r.headers["x-ratelimit-remaining"]) < 500: print('Warning! Approaching rate limit. Backing off.') print('Rate limit remaining:', r.headers["x-ratelimit-remaining"], 'out of', r.headers["x-ratelimit-limit"], 'Period is', r.headers["x-ratelimit-period"]) time.sleep(RATE_LIMIT_BACKOFF) print("-" * 60) r.close() except Exception as e: print(e) return # Just return if we dont get a good value from DD time.sleep(DELAY_BETWEEN) return
def _get_btc_price(self): try: print("Fetching Bitcoin price from network...") r = requests.get( "http://api.coindesk.com/v1/bpi/currentprice/USD.json") j = r.json() btc = float(j["bpi"]["USD"]["rate_float"]) print("Bitcoin price:", btc) self._cache["btc_usd"] = btc r.close() except RuntimeError as e: print("HTTP request failed: ", e)
def tick(): CMD_CENTER_URL = "http://192.168.86.39:5000/api/cmd/Percy" # print("Getting Command") response = requests.get(CMD_CENTER_URL) cmd_text = response.text if cmd_text == "": # print("no commands queued") pass else: print("Command: ", cmd_text) run_cmd(cmd_text)
def _get_net_time(self, rtc): try: print("Fetching current time from network...") r = requests.get("http://worldtimeapi.org/api/ip") trtc = time.mktime(rtc.datetime) j = r.json() tnet = j["unixtime"] + j["raw_offset"] + j["dst_offset"] rtc.datetime = time.localtime(tnet) print("Adjusted DS3231 clock by", trtc - tnet, "seconds.") self._cache["last_refresh"] = tnet r.close() except RuntimeError as e: print("HTTP request failed: ", e)
def test_second_tls_connect_fails(): mocket.getaddrinfo.return_value = ((None, None, None, None, (IP, 80)), ) sock = mocket.Mocket(HEADERS + ENCODED) sock2 = mocket.Mocket(HEADERS + ENCODED) sock3 = mocket.Mocket(HEADERS + ENCODED) mocket.socket.call_count = 0 # Reset call count mocket.socket.side_effect = [sock, sock2, sock3] sock2.connect.side_effect = RuntimeError("error connecting") adafruit_requests.set_socket(mocket, mocket.interface) response = adafruit_requests.get("https://" + HOST + "/testwifi/index.html") sock.send.assert_has_calls([ mock.call(b"testwifi/index.html"), ]) sock.send.assert_has_calls([ mock.call(b"Host: "), mock.call(HOST.encode("utf-8")), mock.call(b"\r\n"), ]) assert response.text == str(ENCODED, "utf-8") host2 = "test.adafruit.com" response = adafruit_requests.get("https://" + host2 + "/get2") sock.connect.assert_called_once_with((HOST, 443), mocket.interface.TLS_MODE) sock2.connect.assert_called_once_with((host2, 443), mocket.interface.TLS_MODE) sock3.connect.assert_called_once_with((host2, 443), mocket.interface.TLS_MODE) # Make sure that the socket is closed after send fails. sock.close.assert_called_once() sock2.close.assert_called_once() assert sock3.close.call_count == 0 assert mocket.socket.call_count == 3
def _get_weather(self): try: print("Fetching weather data from network...") r = requests.get( "http://api.openweathermap.org/data/2.5/weather?id=5383777&units=metric&appid=" + secrets.OPEN_WEATHER_KEY) j = r.json() temperature = float(j["main"]["temp"]) pressure = float(j["main"]["pressure"]) humidity = float(j["main"]["humidity"]) print("Weather:", temperature, pressure, humidity) self._cache["temperature"] = temperature self._cache["pressure"] = pressure self._cache["humidity"] = humidity r.close() except RuntimeError as e: print("HTTP request failed: ", e)
def get_local_time(self, location=None): api_url = None try: aio_username = secrets["aio_username"] aio_key = secrets["aio_key"] except KeyError: raise KeyError( "\n\nOur time service requires a login/password to rate-limit. Please register for a free adafruit.io account and place the user/key in your secrets file under 'aio_username' and 'aio_key'" # pylint: disable=line-too-long ) location = secrets.get("timezone", location) if location: api_url = (TIME_SERVICE + "&tz=%s") % (aio_username, aio_key, location) else: # we'll try to figure it out from the IP address api_url = TIME_SERVICE % (aio_username, aio_key) api_url += TIME_SERVICE_STRFTIME try: response = requests.get(api_url, timeout=10) if response.status_code != 200: raise ValueError(response.text) if self.debug: print("Time request: ", api_url) print("Time reply: ", response.text) times = response.text.split(" ") the_date = times[0] the_time = times[1] year_day = int(times[2]) week_day = int(times[3]) is_dst = None # no way to know yet except KeyError: raise KeyError( "Was unable to lookup the time, try setting secrets['timezone'] according to http://worldtimeapi.org/timezones" ) year, month, mday = [int(x) for x in the_date.split("-")] the_time = the_time.split(".")[0] hours, minutes, seconds = [int(x) for x in the_time.split(":")] now = time.struct_time( (year, month, mday, hours, minutes, seconds, week_day, year_day, is_dst) ) print(now) rtc.RTC().datetime = now # now clean up response.close() response = None gc.collect()
def get(self, url, **kw): """ Pass the Get request to requests and update status LED :param str url: The URL to retrieve data from :param dict data: (Optional) Form data to submit :param dict json: (Optional) JSON data to submit. (Data must be None) :param dict header: (Optional) Header data to include :param bool stream: (Optional) Whether to stream the Response :return: The response from the request :rtype: Response """ if not self.is_connected: self.connect() self.pixel_status((0, 0, 100)) return_val = requests.get(url, **kw) self.pixel_status(0) return return_val
def wget(self, url, filename, *, chunk_size=12000): """Download a url and save to filename location, like the command wget. :param url: The URL from which to obtain the data. :param filename: The name of the file to save the data to. :param chunk_size: how much data to read/write at a time. """ print("Fetching stream from", url) self.neo_status((100, 100, 0)) r = requests.get(url, stream=True) if self._debug: print(r.headers) content_length = int(r.headers["content-length"]) remaining = content_length print("Saving data to ", filename) stamp = time.monotonic() file = open(filename, "wb") for i in r.iter_content(min(remaining, chunk_size)): # huge chunks! self.neo_status((0, 100, 100)) remaining -= len(i) file.write(i) if self._debug: print( "Read %d bytes, %d remaining" % (content_length - remaining, remaining) ) else: print(".", end="") if not remaining: break self.neo_status((100, 100, 0)) file.close() r.close() stamp = time.monotonic() - stamp print( "Created file of %d bytes in %0.1f seconds" % (os.stat(filename)[6], stamp) ) self.neo_status((0, 0, 0)) if not content_length == os.stat(filename)[6]: raise RuntimeError
def get_local_time(): TIME_SERVICE = "https://io.adafruit.com/api/v2/%s/integrations/time/strftime?x-aio-key=%s" TIME_SERVICE_STRFTIME = '&fmt=%25Y-%25m-%25d+%25H%3A%25M%3A%25S.%25L+%25j+%25u+%25z+%25Z' api_url = None try: aio_username = secrets['aio_username'] aio_key = secrets['aio_key'] location = secrets['timezone'] except KeyError: raise KeyError("\n\nOur time service requires a login/password to rate-limit. Please register for a free adafruit.io account and place the user/key in your secrets file under 'aio_username' and 'aio_key'") if location: print("Updating time based on timezone ", location) api_url = (TIME_SERVICE + "&tz=%s") % (aio_username, aio_key, location) else: print("Updating time based on IP address") api_url = TIME_SERVICE % (aio_username, aio_key) api_url += TIME_SERVICE_STRFTIME print("Time API URL: \n", api_url) try: response = requests.get(api_url) if esp._debug: print("Time request: ", api_url) print("Time reply: ", response.text) print("Time reply: ", response.text) times = response.text.split(' ') the_date = times[0] the_time = times[1] year_day = int(times[2]) week_day = int(times[3]) is_dst = None except KeyError: raise KeyError("Was unable to update the time, try setting secrets['timezone'] according to http://worldtimeapi.org/timezones") year, month, mday = [int(x) for x in the_date.split('-')] the_time = the_time.split('.')[0] hours, minutes, seconds = [int(x) for x in the_time.split(':')] now_struct = time.struct_time((year, month, mday, hours, minutes, seconds, week_day, year_day, is_dst)) rtc.RTC().datetime = now_struct response.close() response = None
def get_local_timestamp(location=None): # pylint: disable=line-too-long """Fetch and "set" the local time of this microcontroller to the local time at the location, using an internet time API. :param str location: Your city and country, e.g. ``"New York, US"``. """ # pylint: enable=line-too-long api_url = None try: aio_username = secrets['aio_username'] aio_key = secrets['aio_key'] except KeyError: raise KeyError("\n\nOur time service requires a login/password to rate-limit. Please register for a free adafruit.io account and place the user/key in your secrets file under 'aio_username' and 'aio_key'") # pylint: disable=line-too-long location = secrets.get('timezone', location) if location: print("Getting time for timezone", location) api_url = (TIME_SERVICE + "&tz=%s") % (aio_username, aio_key, location) else: # we'll try to figure it out from the IP address print("Getting time from IP address") api_url = TIME_SERVICE % (aio_username, aio_key) api_url += TIME_SERVICE_TIMESTAMP try: print("api_url:", api_url) response = requests.get(api_url) times = response.text.split(' ') seconds = int(times[0]) tzoffset = times[1] tzhours = int(tzoffset[0:3]) tzminutes = int(tzoffset[3:5]) tzseconds = tzhours * 60 * 60 if tzseconds < 0: tzseconds -= tzminutes * 60 else: tzseconds += tzminutes * 60 print(seconds + tzseconds, tzoffset, tzhours, tzminutes) except KeyError: raise KeyError("Was unable to lookup the time, try setting secrets['timezone'] according to http://worldtimeapi.org/timezones") # pylint: disable=line-too-long # now clean up response.close() response = None gc.collect() return int(seconds + tzseconds)
def fetch(self, url, *, headers=None, timeout=10): """Fetch data from the specified url and return a response object""" gc.collect() if self._debug: print("Free mem: ", gc.mem_free()) # pylint: disable=no-member response = None if self.uselocal: print("*** USING LOCALFILE FOR DATA - NOT INTERNET!!! ***") response = Fake_Requests(LOCALFILE) if not response: self.connect() # great, lets get the data print("Retrieving data...", end="") self.neo_status(STATUS_FETCHING) # yellow = fetching data gc.collect() response = requests.get(url, headers=headers, timeout=timeout) gc.collect() return response
if esp.status == adafruit_esp32spi.WL_IDLE_STATUS: print("ESP32 found and in idle mode") print("Firmware vers.", esp.firmware_version) print("MAC addr:", [hex(i) for i in esp.MAC_address]) for ap in esp.scan_networks(): print("\t%s\t\tRSSI: %d" % (str(ap['ssid'], 'utf-8'), ap['rssi'])) print("Connecting to AP...") while not esp.is_connected: try: esp.connect_AP(secrets['ssid'], secrets['password']) except RuntimeError as e: print("could not connect to AP, retrying: ",e) continue print("Connected to", str(esp.ssid, 'utf-8'), "\tRSSI:", esp.rssi) print("My IP address is", esp.pretty_ip(esp.ip_address)) print("IP lookup adafruit.com: %s" % esp.pretty_ip(esp.get_host_by_name("adafruit.com"))) print("Ping google.com: %d ms" % esp.ping("google.com")) print() print("Fetching json from", JSON_URL) r = requests.get(JSON_URL) print('-'*40) print(r.json()) print('-'*40) r.close() print("Done!")
print("Wiznet5k WebClient Test (no DHCP)") cs = digitalio.DigitalInOut(board.D10) spi_bus = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) # Initialize ethernet interface without DHCP eth = WIZNET5K(spi_bus, cs, is_dhcp=False) # Set network configuration eth.ifconfig = (IP_ADDRESS, SUBNET_MASK, GATEWAY_ADDRESS, DNS_SERVER) # Initialize a requests object with a socket and ethernet interface requests.set_socket(socket, eth) print("Chip Version:", eth.chip) print("MAC Address:", [hex(i) for i in eth.mac_address]) print("My IP address is:", eth.pretty_ip(eth.ip_address)) print("IP lookup adafruit.com: %s" % eth.pretty_ip(eth.get_host_by_name("adafruit.com"))) #eth._debug = True print("Fetching text from", TEXT_URL) r = requests.get(TEXT_URL) print('-' * 40) print(r.text) print('-' * 40) r.close() print()
while not network.is_connected: print("Connecting to network...") network.connect() time.sleep(0.5) print("Network Connected!") print("My IP address is:", fona.local_ip) print("IP lookup adafruit.com: %s" % fona.get_host_by_name("adafruit.com")) # Initialize a requests object with a socket and cellular interface requests.set_socket(cellular_socket, fona) # fona._debug = True print("Fetching text from", TEXT_URL) r = requests.get(TEXT_URL) print("-" * 40) print(r.text) print("-" * 40) r.close() print() print("Fetching json from", JSON_URL) r = requests.get(JSON_URL) print("-" * 40) print(r.json()) print("-" * 40) r.close() print("Done!")