Skip to content

Commit

Permalink
Fastapi Example
Browse files Browse the repository at this point in the history
  • Loading branch information
sonic182 committed Feb 17, 2024
1 parent d725380 commit 3ae8da8
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 10 deletions.
1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -24,3 +24,4 @@ junit/
env/
venv*/
.coverage.*
docs/
2 changes: 1 addition & 1 deletion Makefile
Expand Up @@ -7,7 +7,7 @@ SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = sourcedocs
BUILDDIR = docs
DOCKER_CMD = curl -sL https://deb.nodesource.com/setup_20.x | bash && apt-get update && apt-get install nodejs -y && cd /root && cp -r /app/* . && pip install -r requirements.txt && pip install -e \".[test]\" && pytest
DOCKER_CMD = curl -sL https://deb.nodesource.com/setup_20.x | bash && apt-get update && apt-get install nodejs -y && cd /root && cp -r /app/* . && pip install -r requirements.txt && pip install -e \".[test]\" && ./tests.sh

# Put it first so that "make" without argument is like "make help".
help:
Expand Down
47 changes: 38 additions & 9 deletions sourcedocs/examples.rst
Expand Up @@ -60,18 +60,10 @@ Concurrent Requests
async with aiosonic.HTTPClient() as client:
# asyncio.gather is the key for concurrent requests.
responses = await asyncio.gather(*[client.get(url) for url in urls])
# stream/chunked responses doesn't release the connection acquired
# from the pool until the response has been read, so better to read
# it.
for response in responses:
if response.chunked:
await response.text()
assert all([res.status_code in [200, 301] for res in responses])
loop = asyncio.get_event_loop()
loo.run_until_complete(main())
loop.run_until_complete(main())
Chunked Requests
Expand Down Expand Up @@ -208,3 +200,40 @@ Configure aiosonic logger at debug level to see some logging
loop = asyncio.get_event_loop()
loop.run_until_complete(run())
Fastapi Usage
=============

You need to use the fastapi `dependency system <https://fastapi.tiangolo.com/tutorial/dependencies/>`_ in order to have a common HTTPClient instance

.. code-block:: python
from contextlib import asynccontextmanager
from typing import Union
from aiosonic import HTTPClient
from fastapi import FastAPI
client = HTTPClient()
@asynccontextmanager
async def lifespan(_app: FastAPI):
global client
yield
# useful function to wait all pending requests to finish
await client.wait_requests()
app = FastAPI(lifespan=lifespan)
@app.get("/")
async def home():
assert client, "no client"
url = "https://postman-echo.com/post"
res = await client.post(url, params={"foo": "bar"})
return (await res.json())["args"]

0 comments on commit 3ae8da8

Please sign in to comment.