Tartalomjegyzék

< FastAPI

FastAPI és Tortoise

Függőségek telepítése

pip install fastapi tortoise

Dolgozók

main.py
from fastapi import FastAPI, HTTPException
from tortoise import fields
from tortoise.models import Model
from tortoise.contrib.pydantic import pydantic_model_creator
from tortoise.contrib.fastapi import register_tortoise
 
app = FastAPI()
 
class Employee(Model):
    id = fields.IntField(pk=True)
    name = fields.CharField(50)
    city = fields.CharField(50)
    salary = fields.FloatField()
 
Employee_Pydantic = pydantic_model_creator(Employee, name='name')
EmployeeIn_Pydantic = pydantic_model_creator(Employee, name='namein', exclude_readonly=True)
 
@app.get("/employees")
async def get_employees():
    return await Employee_Pydantic.from_queryset(Employee.all())
 
@app.get("/employees/{emp_id}")
async def get_employee(emp_id: int):
    return await Employee_Pydantic.from_queryset_single(Employee.get(id=emp_id))
 
@app.post('/employees')
async def create_employee(employee: EmployeeIn_Pydantic):
    employee_obj = await Employee.create(**employee.dict(exclude_unset=True))
    return await Employee_Pydantic.from_tortoise_orm(employee_obj)
 
 
@app.put('/employees/{emp_id}')
async def update_employee(emp_id: int, employee: EmployeeIn_Pydantic):
    existing_employee = await Employee.get_or_none(id=emp_id)    
    if existing_employee is None:
        raise HTTPException(status_code=404, detail="Employee not found")        
    existing_employee.name = employee.name
    existing_employee.city = employee.city
    existing_employee.salary = employee.salary    
    await existing_employee.save()    
    return await Employee_Pydantic.from_tortoise_orm(existing_employee)
 
 
@app.delete("/employees/{emp_id}")
async def delete_employee(emp_id: int):
    affected = await Employee.filter(id=emp_id).delete()
    return affected
 
register_tortoise(
    app,
    db_url='sqlite://db2.sqlite3',
    modules={'main': ['main']},
    generate_schemas=True,
    add_exception_handlers=True
)

Futtatás:

pip install uvicorn
python -m uvicorn main:app --reload