You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Implementação da API Assíncrona
Python
from fastapi import FastAPI, Depends, HTTPException
from fastapi_pagination import Page, add_pagination
from sqlalchemy.orm import Session
from models import Atleta
from database import SessionLocal
app = FastAPI()
@app.on_event("startup")
async def startup_event():
global session
session = SessionLocal()
@app.on_event("shutdown")
async def shutdown_event():
global session
session.close()
if nome:
query = query.filter(Atleta.nome.ilike(f"%{nome}%"))
if cpf:
query = query.filter(Atleta.cpf == cpf)
atletas = query.all()
if not atletas:
raise HTTPException(status_code=404, detail="Atleta não encontrado")
return atletas
Endpoint para cadastrar um novo atleta
@app.post("/atletas")
async def
The text was updated successfully, but these errors were encountered:
Instalação das Dependências
bash
pip install fastapi sqlalchemy fastapi-pagination uvicorn
Criação do Modelo de Dados
Python
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from database import Base
class Atleta(Base):
tablename = "atletas"
Configuração do Banco de Dados:
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
engine = create_engine("postgresql://user:password@host:port/database")
Base.metadata.create_all(engine)
SessionLocal = Session(autocommit=False, autoflush=False, bind=engine)
Implementação da API Assíncrona
Python
from fastapi import FastAPI, Depends, HTTPException
from fastapi_pagination import Page, add_pagination
from sqlalchemy.orm import Session
from models import Atleta
from database import SessionLocal
app = FastAPI()
@app.on_event("startup")
async def startup_event():
global session
session = SessionLocal()
@app.on_event("shutdown")
async def shutdown_event():
global session
session.close()
Obter sessão do banco de dados
def get_db(session: Session = Depends(SessionLocal)):
return session
Endpoint para buscar todos os atletas
@app.get("/atletas", response_model=Page[Atleta])
async def get_all_atletas(db: Session = Depends(get_db), limit: int | None = None, offset: int | None = None):
atletas = db.query(Atleta).order_by(Atleta.id).limit(limit).offset(offset).all()
return Page(atletas, len(atletas))
Endpoint para buscar atletas por nome e CPF
@app.get("/atletas", response_model=List[Atleta])
async def get_atleta_by_nome_cpf(nome: str | None = None, cpf: str | None = None, db: Session = Depends(get_db)):
query = db.query(Atleta)
Endpoint para cadastrar um novo atleta
@app.post("/atletas")
async def
The text was updated successfully, but these errors were encountered: