-
Notifications
You must be signed in to change notification settings - Fork 21
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* add async client * create/close single aiohttp session * update template * update example * fix bug in missing content-type exception * session param in init, better teardown and examples * formatting * don't auto-create client session * update example
- Loading branch information
1 parent
d35e284
commit 69b39fb
Showing
9 changed files
with
203 additions
and
54 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,15 +1,66 @@ | ||
try: | ||
import asyncio | ||
import aiohttp | ||
except ModuleNotFoundError: | ||
pass | ||
|
||
from twirp.context import Context | ||
from twirp.exceptions import TwirpServerException | ||
|
||
from generated import haberdasher_twirp, haberdasher_pb2 | ||
|
||
client = haberdasher_twirp.HaberdasherClient("http://localhost:3000") | ||
|
||
try: | ||
response = client.MakeHat( | ||
ctx=Context(), request=haberdasher_pb2.Size(inches=12), server_path_prefix="/twirpy") | ||
if not response.HasField('name'): | ||
print("We didn't get a name!") | ||
print(response) | ||
except TwirpServerException as e: | ||
print(e.code, e.message, e.meta, e.to_dict()) | ||
server_url = "http://localhost:3000" | ||
timeout_s = 5 | ||
|
||
|
||
def main(): | ||
client = haberdasher_twirp.HaberdasherClient(server_url, timeout_s) | ||
|
||
try: | ||
response = client.MakeHat( | ||
ctx=Context(), | ||
request=haberdasher_pb2.Size(inches=12), | ||
server_path_prefix="/twirpy", | ||
) | ||
if not response.HasField("name"): | ||
print("We didn't get a name!") | ||
print(response) | ||
except TwirpServerException as e: | ||
print(e.code, e.message, e.meta, e.to_dict()) | ||
|
||
|
||
async def async_main(): | ||
# The caller must provide their own ClientSession to the twirp client | ||
# either on init or per request, and ensure it is closed properly on app shutdown. | ||
|
||
# NOTE: ClientSession may only be created (or closed) within a coroutine. | ||
session = aiohttp.ClientSession( | ||
server_url, timeout=aiohttp.ClientTimeout(total=timeout_s) | ||
) | ||
client = haberdasher_twirp.AsyncHaberdasherClient(server_url, session=session) | ||
|
||
try: | ||
response = await client.MakeHat( | ||
ctx=Context(), | ||
request=haberdasher_pb2.Size(inches=12), | ||
server_path_prefix="/twirpy", | ||
# Optionally provide a session per request | ||
# session=session, | ||
) | ||
if not response.HasField("name"): | ||
print("We didn't get a name!") | ||
print(response) | ||
except TwirpServerException as e: | ||
print(e.code, e.message, e.meta, e.to_dict()) | ||
finally: | ||
# Close the session (could also use a context manager) | ||
await session.close() | ||
|
||
|
||
if __name__ == "__main__": | ||
if hasattr(haberdasher_twirp, "AsyncHaberdasherClient"): | ||
print("using async client") | ||
asyncio.run(async_main()) | ||
else: | ||
main() |
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,2 @@ | ||
twirp==0.0.2 | ||
uvicorn==0.12.2 | ||
twirp==0.0.8 | ||
uvicorn==0.23.2 |
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -18,6 +18,9 @@ | |
'structlog', | ||
'protobuf' | ||
], | ||
extras_require={ | ||
'async': ['aiohttp'], | ||
}, | ||
test_requires=[ | ||
], | ||
zip_safe=False) |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
import asyncio | ||
import json | ||
from typing import Optional | ||
|
||
import aiohttp | ||
|
||
from . import exceptions | ||
from . import errors | ||
|
||
|
||
class AsyncTwirpClient: | ||
def __init__( | ||
self, address: str, session: Optional[aiohttp.ClientSession] = None | ||
) -> None: | ||
self._address = address | ||
self._session = session | ||
|
||
async def _make_request( | ||
self, *, url, ctx, request, response_obj, session=None, **kwargs | ||
): | ||
headers = ctx.get_headers() | ||
if "headers" in kwargs: | ||
headers.update(kwargs["headers"]) | ||
kwargs["headers"] = headers | ||
kwargs["headers"]["Content-Type"] = "application/protobuf" | ||
|
||
if session is None: | ||
session = self._session | ||
if not isinstance(session, aiohttp.ClientSession): | ||
raise TypeError(f"invalid session type '{type(session).__name__}'") | ||
|
||
try: | ||
async with await session.post( | ||
url=url, data=request.SerializeToString(), **kwargs | ||
) as resp: | ||
if resp.status == 200: | ||
response = response_obj() | ||
response.ParseFromString(await resp.read()) | ||
return response | ||
try: | ||
raise exceptions.TwirpServerException.from_json(await resp.json()) | ||
except (aiohttp.ContentTypeError, json.JSONDecodeError): | ||
raise exceptions.twirp_error_from_intermediary( | ||
resp.status, resp.reason, resp.headers, await resp.text() | ||
) from None | ||
except asyncio.TimeoutError as e: | ||
raise exceptions.TwirpServerException( | ||
code=errors.Errors.DeadlineExceeded, | ||
message=str(e) or "request timeout", | ||
meta={"original_exception": e}, | ||
) | ||
except aiohttp.ServerConnectionError as e: | ||
raise exceptions.TwirpServerException( | ||
code=errors.Errors.Unavailable, | ||
message=str(e), | ||
meta={"original_exception": e}, | ||
) |
This file contains 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
This file contains 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
This file contains 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