Skip to content

Commit 6985b33

Browse files
committed
Create requests_api_github.py
Example script for Github API. Includes some error correction and time based requests. Returns basic stats. Amount of serial prints configurable with debugger booleans.
1 parent 2c38b16 commit 6985b33

File tree

1 file changed

+109
-0
lines changed

1 file changed

+109
-0
lines changed

examples/requests_api_github.py

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
# SPDX-FileCopyrightText: 2022 DJDevon3
2+
# SPDX-License-Identifier: MIT
3+
# Coded for Circuit Python 8.0
4+
"""DJDevon3 Adafruit Feather ESP32-S2 Github_API_Example"""
5+
# pylint: disable=line-too-long
6+
import gc
7+
import time
8+
import ssl
9+
import wifi
10+
import json
11+
import socketpool
12+
import adafruit_requests
13+
14+
# Github developer token required.
15+
# Ensure these are uncommented and in secrets.py or .env
16+
# "Github_username": "Your Github Username",
17+
# "Github_token": "Your long API token",
18+
19+
# Initialize WiFi Pool (There can be only 1 pool & top of script)
20+
pool = socketpool.SocketPool(wifi.radio)
21+
22+
# Time between API refreshes
23+
# 900 = 15 mins, 1800 = 30 mins, 3600 = 1 hour
24+
sleep_time = 900
25+
26+
try:
27+
from secrets import secrets
28+
except ImportError:
29+
print("Secrets File Import Error")
30+
raise
31+
32+
if sleep_time < 60:
33+
sleep_time_conversion = "seconds"
34+
sleep_int = sleep_time
35+
elif 60 <= sleep_time < 3600:
36+
sleep_int = sleep_time / 60
37+
sleep_time_conversion = "minutes"
38+
elif 3600 <= sleep_time < 86400:
39+
sleep_int = sleep_time / 60 / 60
40+
sleep_time_conversion = "hours"
41+
else:
42+
sleep_int = sleep_time / 60 / 60 / 24
43+
sleep_time_conversion = "days"
44+
45+
github_header = {'Authorization':' token ' + secrets["Github_token"]}
46+
GH_SOURCE = (
47+
"https://api.github.com/users/"
48+
+ secrets["Github_username"]
49+
)
50+
51+
# Connect to Wi-Fi
52+
print("\n===============================")
53+
print("Connecting to WiFi...")
54+
requests = adafruit_requests.Session(pool, ssl.create_default_context())
55+
while not wifi.radio.ipv4_address:
56+
try:
57+
wifi.radio.connect(secrets['ssid'], secrets['password'])
58+
except ConnectionError as e:
59+
print("Connection Error:", e)
60+
print("Retrying in 10 seconds")
61+
time.sleep(10)
62+
gc.collect()
63+
print("Connected!\n")
64+
65+
while True:
66+
try:
67+
print("\nAttempting to GET GITHUB Stats!") # --------------------------------
68+
# Print Request to Serial
69+
debug_request = False # Set true to see full request
70+
if debug_request:
71+
print("Full API GET URL: ", GH_SOURCE)
72+
print("===============================")
73+
try:
74+
github_response = requests.get(url=GH_SOURCE, headers=github_header).json()
75+
except ConnectionError as e:
76+
print("Connection Error:", e)
77+
print("Retrying in 10 seconds")
78+
79+
# Print Response to Serial
80+
debug_response = False # Set true to see full response
81+
if debug_response:
82+
dump_object = json.dumps(github_response)
83+
print("JSON Dump: ", dump_object)
84+
85+
# Print Keys to Serial
86+
gh_debug_keys = True # Set True to print Serial data
87+
if gh_debug_keys:
88+
89+
github_id = github_response['id']
90+
print("UserID: ", github_id)
91+
92+
github_username = github_response['name']
93+
print("Username: ", github_username)
94+
95+
github_followers = github_response['followers']
96+
print("Followers: ", github_followers)
97+
98+
print("Monotonic: ", time.monotonic())
99+
100+
print("\nFinished!")
101+
print("Next Update in %s %s" % (int(sleep_int), sleep_time_conversion))
102+
print("===============================")
103+
gc.collect()
104+
# pylint: disable=broad-except
105+
except (ValueError, RuntimeError) as e:
106+
print("Failed to get data, retrying\n", e)
107+
time.sleep(60)
108+
continue
109+
time.sleep(sleep_time)

0 commit comments

Comments
 (0)