Skip to content

Commit 1f45f5b

Browse files
committed
Add example for dealing with multiple cookies
1 parent bacfa8d commit 1f45f5b

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

examples/requests_multiple_cookies.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# SPDX-FileCopyrightText: 2022 Alec Delaney
2+
# SPDX-License-Identifier: MIT
3+
4+
"""
5+
This example was written for the MagTag; changes may be needed
6+
for connecting to the internet depending on your device.
7+
"""
8+
9+
import ssl
10+
import wifi
11+
import socketpool
12+
import adafruit_requests
13+
14+
COOKIE_TEST_URL = "https://www.adafruit.com"
15+
16+
# Get wifi details and more from a secrets.py file
17+
try:
18+
from secrets import secrets
19+
except ImportError:
20+
print("WiFi secrets are kept in secrets.py, please add them there!")
21+
raise
22+
23+
# Connect to the Wi-Fi network
24+
print("Connecting to %s"%secrets["ssid"])
25+
wifi.radio.connect(secrets["ssid"], secrets["password"])
26+
27+
# Set up the requests library
28+
pool = socketpool.SocketPool(wifi.radio)
29+
requests = adafruit_requests.Session(pool, ssl.create_default_context())
30+
31+
# GET from the URL
32+
print("Fetching multiple cookies from", COOKIE_TEST_URL)
33+
response = requests.get(COOKIE_TEST_URL)
34+
35+
# Spilt up the cookies by ", "
36+
elements = response.headers["set-cookie"].split(", ")
37+
38+
# NOTE: Some cookies use ", " when describing dates. This code will iterate through
39+
# the previously split up 'set-cookie' header value and piece back together cookies
40+
# that were accidentally split up for this reason
41+
days_of_week = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")
42+
elements_iter = iter(elements)
43+
cookie_list = []
44+
for element in elements_iter:
45+
captured_day = [day for day in days_of_week if element.endswith(day)]
46+
if captured_day:
47+
cookie_list.append(element + ", " + next(elements_iter))
48+
else:
49+
cookie_list.append(element)
50+
51+
# Pring the information about the cookies
52+
print("Number of cookies:", len(cookie_list))
53+
print("")
54+
print("Cookies received:")
55+
print("-" * 40)
56+
for cookie in cookie_list:
57+
print(cookie)
58+
print("-" * 40)

0 commit comments

Comments
 (0)