kopia lustrzana https://github.com/micropython/micropython-lib
urequests: Add ability to parse response headers.
This is controlled by parse_headers param to request(), which defaults to True for compatibility with upstream requests. In this case, headers are available as .headers of Response objects. They are however normal (not case-insensitive) dict. If parse_headers=False, old behavior of ignore response headers is used, which saves memory on the dict. Finally, parse_headers can be a custom function which can e.g. parse only subset of headers (again, to save memory).pull/500/head
rodzic
db4c739863
commit
5854ae1286
|
@ -33,7 +33,7 @@ class Response:
|
||||||
return ujson.loads(self.content)
|
return ujson.loads(self.content)
|
||||||
|
|
||||||
|
|
||||||
def request(method, url, data=None, json=None, headers={}, stream=None):
|
def request(method, url, data=None, json=None, headers={}, stream=None, parse_headers=True):
|
||||||
try:
|
try:
|
||||||
proto, dummy, host, path = url.split("/", 3)
|
proto, dummy, host, path = url.split("/", 3)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
|
@ -55,6 +55,10 @@ def request(method, url, data=None, json=None, headers={}, stream=None):
|
||||||
ai = usocket.getaddrinfo(host, port, 0, usocket.SOCK_STREAM)
|
ai = usocket.getaddrinfo(host, port, 0, usocket.SOCK_STREAM)
|
||||||
ai = ai[0]
|
ai = ai[0]
|
||||||
|
|
||||||
|
resp_d = None
|
||||||
|
if parse_headers is not False:
|
||||||
|
resp_d = {}
|
||||||
|
|
||||||
s = usocket.socket(ai[0], ai[1], ai[2])
|
s = usocket.socket(ai[0], ai[1], ai[2])
|
||||||
try:
|
try:
|
||||||
s.connect(ai[-1])
|
s.connect(ai[-1])
|
||||||
|
@ -98,6 +102,14 @@ def request(method, url, data=None, json=None, headers={}, stream=None):
|
||||||
raise ValueError("Unsupported " + l)
|
raise ValueError("Unsupported " + l)
|
||||||
elif l.startswith(b"Location:") and not 200 <= status <= 299:
|
elif l.startswith(b"Location:") and not 200 <= status <= 299:
|
||||||
raise NotImplementedError("Redirects not yet supported")
|
raise NotImplementedError("Redirects not yet supported")
|
||||||
|
if parse_headers is False:
|
||||||
|
pass
|
||||||
|
elif parse_headers is True:
|
||||||
|
l = str(l, "utf-8")
|
||||||
|
k, v = l.split(":", 1)
|
||||||
|
resp_d[k] = v.strip()
|
||||||
|
else:
|
||||||
|
parse_headers(l, resp_d)
|
||||||
except OSError:
|
except OSError:
|
||||||
s.close()
|
s.close()
|
||||||
raise
|
raise
|
||||||
|
@ -105,6 +117,8 @@ def request(method, url, data=None, json=None, headers={}, stream=None):
|
||||||
resp = Response(s)
|
resp = Response(s)
|
||||||
resp.status_code = status
|
resp.status_code = status
|
||||||
resp.reason = reason
|
resp.reason = reason
|
||||||
|
if resp_d is not None:
|
||||||
|
resp.headers = resp_d
|
||||||
return resp
|
return resp
|
||||||
|
|
||||||
|
|
||||||
|
|
Ładowanie…
Reference in New Issue