23 Mar 17:37
from typing import Annotated
import os
import yaml
from fastapi import FastAPI, Form
from fastapi.responses import HTMLResponse, RedirectResponse
import uvicorn
app = FastAPI()
DB_FILE = "products.yaml"
def load_data():
if not os.path.exists(DB_FILE):
data = {
"Kategoria 1": ["Produkt 1", "Produkt 2"],
"Kategoria 2": ["Produkt 3", "Produkt 4"]
}
with open(DB_FILE, "w", encoding="utf-8") as f:
yaml.safe_dump(data, f, allow_unicode=True)
with open(DB_FILE, "r", encoding="utf-8") as f:
data = yaml.safe_load(f)
if data is None:
data = {}
return data
def save_data(data):
with open(DB_FILE, "w", encoding="utf-8") as f:
yaml.safe_dump(data, f, allow_unicode=True)
@app.get("/", response_class=HTMLResponse)
def index():
data = load_data()
html = "<html><body>"
html += "<h1>Kategorie</h1>"
html += "<ul>"
for category in data:
html += f'<li><a href="/category/{category}">{category}</a></li>'
html += "</ul>"
html += "<h2>Dodaj kategorię</h2>"
html += """
<form action="/add_category" method="post">
<input type="text" name="category_name">
<button type="submit">Dodaj</button>
</form>
"""
html += "</body></html>"
return html
@app.get("/category/{category}", response_class=HTMLResponse)
def show_category(category: str):
data = load_data()
html = "<html><body>"
html += '<a href="/">Powrót</a>'
html += f"<h1>Kategoria: {category}</h1>"
if category in data:
html += "<ul>"
for i, product in enumerate(data[category]):
html += f"""
<li>
{product}
<form action="/delete_product" method="post" style="display:inline;">
<input type="hidden" name="category" value="{category}">
<input type="hidden" name="product_index" value="{i}">
<button type="submit">Usuń</button>
</form>
</li>
"""
html += "</ul>"
html += "<h2>Dodaj produkt</h2>"
html += f"""
<form action="/add_product" method="post">
<input type="hidden" name="category" value="{category}">
<input type="text" name="product_name">
<button type="submit">Dodaj</button>
</form>
"""
else:
html += "<p>Nie ma takiej kategorii</p>"
html += "</body></html>"
return html
@app.post("/add_category")
def add_category(category_name: Annotated[str, Form()]):
data = load_data()
name = category_name.strip()
if name != "" and name not in data:
data[name] = []
save_data(data)
return RedirectResponse(url="/", status_code=303)
@app.post("/add_product")
def add_product(
category: Annotated[str, Form()],
product_name: Annotated[str, Form()]
):
data = load_data()
name = product_name.strip()
if category in data and name != "":
data[category].append(name)
save_data(data)
return RedirectResponse(url=f"/category/{category}", status_code=303)
@app.post("/delete_product")
def delete_product(
category: Annotated[str, Form()],
product_index: Annotated[int, Form()]
):
data = load_data()
if category in data:
if product_index >= 0 and product_index < len(data[category]):
del data[category][product_index]
save_data(data)
return RedirectResponse(url=f"/category/{category}", status_code=303)
if __name__ == "__main__":
uvicorn.run(app, host="127.0.0.1", port=8000)