Skip to content
Myr

utils.py

This file

Path

tests/dispatch/utils.py

112 lines · 3.5 KiB · Python

Last changed by

Encapsulate http_version into BaseStreamflorimondmancabefore adoptionfdb1359

History of this file

Take it

Handle early connection closes (#103)Tom Christiebefore adoptionb9c8a15

line 1why, one step back
1import asyncio

Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af

lines 2–8why, one step back
2import ssl
3import typing45import h2.config6import h2.connection7import h2.events8

Unify BaseReader and BaseWriter as BaseStreamflorimondmancabefore adoption14eb81f

line 9why, one step back
9from httpx import AsyncioBackend, BaseStream, Request, TimeoutConfig

Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af

lines 10–14why, one step back
10
1112class MockHTTP2Backend(AsyncioBackend):13 def __init__(self, app):14 self.app = app

Check for connection aliveness on pool re-acquiry (#111)Tom Christiebefore adoption025240c

line 15why, one step back
15 self.server = None

Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af

lines 16–22why, one step back
16
17 async def connect(18 self,19 hostname: str,20 port: int,21 ssl_context: typing.Optional[ssl.SSLContext],22 timeout: TimeoutConfig,

Encapsulate http_version into BaseStreamflorimondmancabefore adoptionfdb1359

line 23why, one step back
23 ) -> BaseStream:

Check for connection aliveness on pool re-acquiry (#111)Tom Christiebefore adoption025240c

line 24why, one step back
24 self.server = MockHTTP2Server(self.app)

Encapsulate http_version into BaseStreamflorimondmancabefore adoptionfdb1359

line 25why, one step back
25 return self.server

Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af

lines 26–27why, one step back
26
27

Unify BaseReader and BaseWriter as BaseStreamflorimondmancabefore adoption14eb81f

line 28why, one step back
28class MockHTTP2Server(BaseStream):

Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af

lines 29–34why, one step back
29 def __init__(self, app):
30 config = h2.config.H2Configuration(client_side=False)31 self.conn = h2.connection.H2Connection(config=config)32 self.app = app33 self.buffer = b""34 self.requests = {}

Check disconnections on connection reacquiry (#145)Tom Christiebefore adoptionec365c0

line 35why, one step back
35 self.close_connection = False

Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af

line 36why, one step back
36

Unify BaseReader and BaseWriter as BaseStreamflorimondmancabefore adoption14eb81f

line 37why, one step back
37 # Stream interface

Encapsulate http_version into BaseStreamflorimondmancabefore adoptionfdb1359

lines 38–40why, one step back
38
39 def get_http_version(self) -> str:40 return "HTTP/2"

Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af

line 41why, one step back
41

Read/Write timeout modes (#104)Tom Christiebefore adoptionf4f05e3

line 42why, one step back
42 async def read(self, n, timeout, flag=None) -> bytes:

Handle early connection closes (#103)Tom Christiebefore adoptionb9c8a15

line 43why, one step back
43 await asyncio.sleep(0)

Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af

lines 44–62why, one step back
44 send, self.buffer = self.buffer[:n], self.buffer[n:]
45 return send4647 def write_no_block(self, data: bytes) -> None:48 events = self.conn.receive_data(data)49 self.buffer += self.conn.data_to_send()50 for event in events:51 if isinstance(event, h2.events.RequestReceived):52 self.request_received(event.headers, event.stream_id)53 elif isinstance(event, h2.events.DataReceived):54 self.receive_data(event.data, event.stream_id)55 elif isinstance(event, h2.events.StreamEnded):56 self.stream_complete(event.stream_id)5758 async def write(self, data: bytes, timeout) -> None:59 self.write_no_block(data)6061 async def close(self) -> None:62 pass

Check disconnections on connection reacquiry (#145)Tom Christiebefore adoptionec365c0

lines 63–65why, one step back
63
64 def is_connection_dropped(self) -> bool:65 return self.close_connection

Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af

lines 66–106why, one step back
66
67 # Server implementation6869 def request_received(self, headers, stream_id):70 """71 Handler for when the initial part of the HTTP request is received.72 """73 if stream_id not in self.requests:74 self.requests[stream_id] = []75 self.requests[stream_id].append({"headers": headers, "data": b""})7677 def receive_data(self, data, stream_id):78 """79 Handler for when a data part of the HTTP request is received.80 """81 self.requests[stream_id][-1]["data"] += data8283 def stream_complete(self, stream_id):84 """85 Handler for when the HTTP request is completed.86 """87 request = self.requests[stream_id].pop(0)88 if not self.requests[stream_id]:89 del self.requests[stream_id]9091 headers_dict = dict(request["headers"])9293 method = headers_dict[b":method"].decode("ascii")94 url = "%s://%s%s" % (95 headers_dict[b":scheme"].decode("ascii"),96 headers_dict[b":authority"].decode("ascii"),97 headers_dict[b":path"].decode("ascii"),98 )99 headers = [(k, v) for k, v in request["headers"] if not k.startswith(b":")]100 data = request["data"]101102 # Call out to the app.103 request = Request(method, url, headers=headers, data=data)104 response = self.app(request)105106 # Write the response to the buffer.

Status code tweaks (#77)Tom Christiebefore adoptionc12c271

line 107why, one step back
107 status_code_bytes = str(response.status_code).encode("ascii")

Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af

lines 108–112why, one step back
108 response_headers = [(b":status", status_code_bytes)] + response.headers.raw
109110 self.conn.send_headers(stream_id, response_headers)111 self.conn.send_data(stream_id, response.content, end_stream=True)112 self.buffer += self.conn.data_to_send()