Created
October 3, 2020 14:27
-
-
Save tomchristie/0320359beb6d79b2519ba139ecc00b72 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from contextlib import contextmanager | |
class Transport: | |
@contextmanager | |
def request(self, method, url, headers=None, stream=None): | |
connection_closed = False | |
def content(): | |
for chunk in [b"Hello", b", ", b"world", b"!"]: | |
if connection_closed: | |
raise RuntimeError("Connection closed") | |
yield chunk | |
status_code = 200 | |
headers = {"Content-Length": "13"} | |
stream = content() | |
yield status_code, headers, stream | |
connection_closed = True | |
class Response: | |
def __init__(self, status_code, headers, stream): | |
self.status_code = status_code | |
self.headers = headers | |
self.stream = stream | |
def read(self): | |
self.body = b''.join([chunk for chunk in self.stream]) | |
class Client: | |
def __init__(self): | |
self.transport = Transport() | |
def get(self, url, headers=None, stream=None): | |
with self.transport.request("GET", url, headers, stream) as raw_resp: | |
status_code, headers, stream = raw_resp | |
response = Response(status_code, headers, stream) | |
response.read() | |
return response | |
client = Client() | |
response = client.get("https://www.example.org") | |
print(response.status_code, response.body) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment