[[oktatas:web:back-end_framework:fastapi|< FastAPI]]
====== FastAPI és SQLAlchemy ======
* **Szerző:** Sallai András
* Copyright (c) 2024, Sallai András
* Szerkesztve: 2024
* Licenc: [[https://creativecommons.org/licenses/by-sa/4.0/|CC BY-SA 4.0]]
* Web: https://szit.hu
===== Függőségek telepítése =====
pip install fastapi sqlalchemy
===== Dolgozók =====
from fastapi import FastAPI, Depends
from pydantic import BaseModel
from sqlalchemy import create_engine, Column, Integer, String, Double
from sqlalchemy.orm import sessionmaker, Session
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:///db.sqlite', connect_args={'check_same_thread': False})
SessionLocal = sessionmaker(engine)
Base = declarative_base()
class Employee(Base):
__tablename__ = 'employees'
id = Column(Integer, primary_key=True)
name = Column(String)
city = Column(String)
salary = Column(Double)
Base.metadata.create_all(engine)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
class EmployeeBase(BaseModel):
name: str
app = FastAPI()
@app.post('/employees')
def index(employee: EmployeeBase, db: Session = Depends(get_db)):
db_employee = Employee(name=employee.name)
db.add(db_employee)
db.commit()
db.refresh(db_employee)
return db_employee
@app.get('/employees')
def get_employees(db: Session = Depends(get_db)):
employees = db.query(Employee).all()
return {"employees": employees}
Futtatás:
pip install uvicorn
python -m uvicorn main:app --reload