from fastapi import FastAPI import requests from fastapi.responses import FileResponse import uvicorn import hashlib import pathlib import logging app = FastAPI() logger = logging.getLogger(__name__) cachepath = pathlib.Path('./cache') if not cachepath.is_dir(): cachepath.mkdir() def fetch_url(url): urlhash = hashlib.sha1(url.encode('utf8')).hexdigest() cachefile = (cachepath/urlhash) if not cachefile.is_file(): logger.info(f"caching file {cachefile} for {url}") r = requests.get(url, allow_redirects=True) open(cachefile, 'wb').write(r.content) return FileResponse(cachefile) @app.get("/{url:path}") async def root(url): return fetch_url(url) if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=8000)