Загрузка данных


-----------------
main_api.py
-----------------
from fastapi import FastAPI
from sqlmodel import SQLModel, Field, create_engine, Session, select
from typing import Optional, List

class Product(SQLModel, table=True):
    __tablename__: str = "products"
    rowid: Optional[int] = Field(default=None, primary_key=True)
    productName: str
    productVendor: str
    buyPrice: float

engine = create_engine("sqlite:///data.sqlite", connect_args={"check_same_thread": False})
SQLModel.metadata.create_all(engine)
app = FastAPI()

@app.get("/products")
def get_products(name: Optional[str] = None):
    with Session(engine) as session:
        if name:
            statement = select(Product).where(Product.productName.contains(name))
        return session.exec(statement).all()

@app.post("/add")
def add_product(product: Product):
    with Session(engine) as session:
        session.add(product)
        session.commit()
        return {"status": "success"}

-----------------
main.py
-----------------
from flask import Flask, render_template, request,redirect,url_for
import requests

app = Flask(__name__)
#! ссылка на наш сервер с базой данных
API_URL = "http://127.0.0.1:8000"

@app.route('/')
def index():
    search = request.args.get('search', '')
    response = requests.get(f"{API_URL}/products", params={"name": search})
    
    try:
        products = response.json()
    except:
        products = []
        
    return render_template('index.html', products=products)

@app.route('/add', methods=['POST'])
def add_product():
    new_product = {
        "productName": request.form.get("productName"),
        "productVendor": request.form.get("productVendor"),
        "buyPrice": float(request.form.get("buyPrice", 0))
    }
    #! new_product = {"productName":"Playstation 5", "productVendor":"Sony","buyprice":"60000"}

    requests.post(f"{API_URL}/add", json=new_product)
    return redirect(url_for('index'))

if __name__ == "__main__":
    app.run(port=5000)

-----------------
index.html
-----------------
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sait timohi</title>
</head>
<body>
    <form action="/" method="GET">
        <input type="text" name="search" placeholder="Поиск товара...">
        <button type="submit">Найти</button>
    </form>


    <h3>Добавить товар/книгу</h3>
        <form action="/add" method="POST">
            <input type="text" name="productName" placeholder="Название..." required><br><br>
            <input type="text" name="productVendor" placeholder="Вендор/Автор..." required><br><br>
            <input type="number" step="0.01" name="buyPrice" placeholder="Цена..." required><br><br>
            <button type="submit">Сохранить</button>
        </form>

    <ul>
        {% for p in products %}
            <li>Название:{{ p.productName }} — Цена:{{ p.buyPrice }}$ (Вендор: {{ p.productVendor }})</li>
        {% endfor %}
    </ul>
    
</body>
</html>