Update app.py
Browse files
app.py
CHANGED
|
@@ -1,49 +1,37 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
from fastapi import FastAPI, Request
|
| 3 |
-
import
|
|
|
|
| 4 |
import os
|
| 5 |
|
| 6 |
app = FastAPI()
|
| 7 |
-
|
| 8 |
|
| 9 |
-
#
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
f.write("")
|
| 14 |
-
|
| 15 |
-
init_storage()
|
| 16 |
|
| 17 |
def read_data():
|
| 18 |
-
with open(
|
| 19 |
return f.read()
|
| 20 |
|
| 21 |
-
def write_data(
|
| 22 |
-
with open(
|
| 23 |
-
f.write(
|
| 24 |
-
|
| 25 |
-
# Gradio UI
|
| 26 |
-
def show_latest_data():
|
| 27 |
-
return read_data()
|
| 28 |
-
|
| 29 |
-
with gr.Blocks() as gr_app:
|
| 30 |
-
gr.Markdown("## Latest Sent Text")
|
| 31 |
-
output = gr.Textbox(label="Stored Text", value=read_data(), interactive=False)
|
| 32 |
-
refresh_btn = gr.Button("Refresh")
|
| 33 |
-
refresh_btn.click(fn=show_latest_data, inputs=[], outputs=output)
|
| 34 |
|
| 35 |
-
# Store endpoint
|
| 36 |
@app.get("/store")
|
| 37 |
-
async def
|
| 38 |
-
|
| 39 |
-
if
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from fastapi import FastAPI, Request
|
| 2 |
+
from fastapi.responses import HTMLResponse, RedirectResponse
|
| 3 |
+
import urllib.parse
|
| 4 |
import os
|
| 5 |
|
| 6 |
app = FastAPI()
|
| 7 |
+
STORAGE_FILE = "data.txt"
|
| 8 |
|
| 9 |
+
# Initialize file
|
| 10 |
+
if not os.path.exists(STORAGE_FILE):
|
| 11 |
+
with open(STORAGE_FILE, "w") as f:
|
| 12 |
+
f.write("")
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
def read_data():
|
| 15 |
+
with open(STORAGE_FILE, "r") as f:
|
| 16 |
return f.read()
|
| 17 |
|
| 18 |
+
def write_data(data: str):
|
| 19 |
+
with open(STORAGE_FILE, "w") as f:
|
| 20 |
+
f.write(data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
|
|
|
| 22 |
@app.get("/store")
|
| 23 |
+
async def store(request: Request):
|
| 24 |
+
lists = request.query_params.get("lists")
|
| 25 |
+
if lists:
|
| 26 |
+
decoded = urllib.parse.unquote(lists)
|
| 27 |
+
write_data(decoded)
|
| 28 |
+
return RedirectResponse(url="/") # Redirect back to main page
|
| 29 |
+
return {"status": "error", "message": "Missing 'lists' query parameter."}
|
| 30 |
+
|
| 31 |
+
@app.get("/", response_class=HTMLResponse)
|
| 32 |
+
async def index():
|
| 33 |
+
stored_data = urllib.parse.quote(read_data())
|
| 34 |
+
with open("index.html", "r", encoding="utf-8") as f:
|
| 35 |
+
html = f.read()
|
| 36 |
+
# Inject the stored data into the ?lists= param
|
| 37 |
+
return HTMLResponse(content=html.replace("?lists=", f"?lists={stored_data}"), status_code=200)
|