| import os |
| from fastapi import FastAPI, Request |
| from fastapi.responses import PlainTextResponse, JSONResponse |
| import uvicorn |
|
|
| |
| |
| try: |
| os.makedirs("/data", exist_ok=True) |
| STATE = "/data/current_url.txt" |
| except OSError: |
| STATE = os.path.join(os.getcwd(), "current_url.txt") |
|
|
| app = FastAPI() |
|
|
|
|
| def read() -> str: |
| try: |
| with open(STATE) as f: |
| return f.read().strip() |
| except FileNotFoundError: |
| return "" |
|
|
|
|
| @app.get("/") |
| @app.get("/url") |
| async def get_url(): |
| |
| return PlainTextResponse(read(), headers={"Cache-Control": "no-store"}) |
|
|
|
|
| @app.post("/url") |
| async def set_url(request: Request): |
| body = (await request.body()).decode().strip() |
| if not body: |
| return JSONResponse({"error": "empty body"}, status_code=400) |
| with open(STATE, "w") as f: |
| f.write(body) |
| return JSONResponse({"ok": True, "url": body}) |
|
|
|
|
| if __name__ == "__main__": |
| uvicorn.run(app, host="0.0.0.0", port=7860) |
|
|