-
Notifications
You must be signed in to change notification settings - Fork 21
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
async client #50
Merged
Merged
async client #50
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
bcb9560
add async client
chadawagner 53c38c9
create/close single aiohttp session
chadawagner e648d9e
update template
chadawagner 6d270a3
update example
chadawagner f54d2fd
fix bug in missing content-type exception
chadawagner 814dff4
session param in init, better teardown and examples
chadawagner 744006e
formatting
chadawagner 15daba4
don't auto-create client session
chadawagner 183e5ff
update example
chadawagner File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
#46