Skip to content

Commit

Permalink
Allow connection to be used as an async context manager
Browse files Browse the repository at this point in the history
  • Loading branch information
a-feld committed Nov 13, 2021
1 parent d9c4635 commit e1db1f8
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 10 deletions.
13 changes: 13 additions & 0 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,16 @@ Additionally, :py:meth:`pywreck.request` is provided for custom HTTP methods.
:hidden:

api

Reusing Connections
===================

Creating TCP connections and negotiating TLS can sometimes be expensive. An API
is provided to allow for multiple HTTP requests on the same connection.

.. code-block:: python
async with await pywreck.Connection.create("www.example.com") as conn:
for _ in range(2):
response = await conn.request("HEAD", "/")
print(response)
14 changes: 13 additions & 1 deletion src/pywreck/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
import os.path
import ssl
from dataclasses import dataclass
from typing import Dict, Optional, Union
from types import TracebackType
from typing import Dict, Optional, Type, Union

try:
with open(os.path.join(os.path.dirname(__file__), "version.txt")) as f:
Expand Down Expand Up @@ -121,6 +122,9 @@ async def create(
reader, writer = await asyncio.open_connection(host, port, ssl=ssl)
return Connection(reader, writer, host, timeout)

async def __aenter__(self) -> "Connection":
return self

async def request(
self,
method: str,
Expand Down Expand Up @@ -219,6 +223,14 @@ async def request(

return Response(status, response_headers, response_data)

async def __aexit__(
self,
exc: Optional[Type[BaseException]],
value: Optional[BaseException],
tb: Optional[TracebackType],
) -> None:
await self.close()

async def close(self) -> None:
"""Close the connection"""
writer = self._writer
Expand Down
17 changes: 8 additions & 9 deletions tests/test_pywreck.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,15 +123,14 @@ async def _async():
timeout=None,
)

for _ in range(2):
response = await connection.request(
"GET",
"/",
headers={"user-agent": "pywreck test, yo!"},
)
validate_response(response)

await connection.close()
async with connection:
for _ in range(2):
response = await connection.request(
"GET",
"/",
headers={"user-agent": "pywreck test, yo!"},
)
validate_response(response)

loop.run_until_complete(_async())

Expand Down

0 comments on commit e1db1f8

Please sign in to comment.