Skip to content

Commit 63e3894

Browse files
committed
python-ecosys/requests: Add User-Agent string.
The HTTP User-Agent string is very useful if malfunctioning IoT devices start putting excessive load on a server. It allows the server operator to ban just the malfunctioning devices, not all users. It's also a SHOULD in the HTTP specification. Add it, enabled by default, but with options to override or disable it.
1 parent e03a0fb commit 63e3894

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

python-ecosys/requests/requests/__init__.py

+26
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,16 @@
11
import usocket
22

33

4+
def _make_user_agent():
5+
import sys
6+
comment = sys.implementation._machine
7+
comment = comment.replace('\\', '\\\\').replace('(', '\\(').replace(')', '\\)')
8+
ua = "MicroPython/{}.{}.{} ({})".format(*sys.implementation[1][:3], comment)
9+
return ua
10+
11+
default_user_agent = _make_user_agent()
12+
13+
414
class Response:
515
def __init__(self, f):
616
self.raw = f
@@ -43,6 +53,7 @@ def request(
4353
auth=None,
4454
timeout=None,
4555
parse_headers=True,
56+
user_agent=True
4657
):
4758
redirect = None # redirection url, None means no redirection
4859
chunked_data = data and getattr(data, "__next__", None) and not getattr(data, "__len__", None)
@@ -65,6 +76,17 @@ def request(
6576
basic_auth_header = b"{}:{}".format(username, password)
6677
basic_auth_header = ubinascii.b2a_base64(basic_auth_header)[:-1]
6778

79+
if user_agent:
80+
if user_agent is True:
81+
# Use the standard User-Agent
82+
user_agent = default_user_agent
83+
elif user_agent[0] == ' ':
84+
# It's a suffix to append to the standard User-Agent
85+
user_agent = default_user_agent + user_agent
86+
87+
if user_agent:
88+
user_agent = user_agent.encode('ascii')
89+
6890
try:
6991
proto, dummy, host, path = url.split("/", 3)
7092
except ValueError:
@@ -121,6 +143,10 @@ def request(
121143
s.write(b"Authorization: Basic ")
122144
s.write(basic_auth_header)
123145
s.write(b"\r\n")
146+
if user_agent:
147+
s.write(b"User-Agent: ")
148+
s.write(user_agent)
149+
s.write(b"\r\n")
124150

125151
# Iterate over keys to avoid tuple alloc
126152
for k in headers:

0 commit comments

Comments
 (0)