#!/usr/bin/env python3
import collections
from asyncio import Future
from typing import Dict, List, Tuple
from fastapi import FastAPI, HTTPException, Request
todos: Dict[str, List[Tuple[Future, Request]]] = collections.defaultdict(list)
app = FastAPI()
@app.get("/{token:path}")
async def get(token: str, request: Request):
future = Future()
todos[token].append((future, request))
return await future
@app.post("/{token:path}")
async def post(token: str, payload: dict = {}):
while True:
try:
future, request = todos[token].pop()
if await request.is_disconnected():
future.set_result(None)
else:
future.set_result(payload)
return {"client": "{}:{}".format(*request.client)}
except IndexError:
raise HTTPException(status_code=404)