Created
May 15, 2021 10:59
-
-
Save stlk/d89a65f753066bdcde9430370a687561 to your computer and use it in GitHub Desktop.
fastapi background
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
from fastapi import BackgroundTasks, FastAPI | |
import aiohttp | |
import asyncio | |
app = FastAPI() | |
async def send_request(): | |
async with aiohttp.ClientSession() as session: | |
async with session.get("https://httpdump.io/") as response: | |
print("Status:", response.status) | |
print("Content-type:", response.headers['content-type']) | |
html = await response.text() | |
print("Body:", html[:15], "...") | |
async def send_request_background(): | |
await send_request() | |
await asyncio.sleep(10) | |
await send_request() | |
@app.get("/") | |
async def read_root(background_tasks: BackgroundTasks): | |
background_tasks.add_task(send_request_background) | |
return {"Hello": "World"} | |
@app.get("/items/{item_id}") | |
async def read_item(item_id: int): | |
return {"item_id": item_id} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment