Skip to content

Instantly share code, notes, and snippets.

@stlk
Created May 15, 2021 10:59
Show Gist options
  • Save stlk/d89a65f753066bdcde9430370a687561 to your computer and use it in GitHub Desktop.
Save stlk/d89a65f753066bdcde9430370a687561 to your computer and use it in GitHub Desktop.
fastapi background
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