Update generated backend for blog_app with entities: tags, user, and

This commit is contained in:
Backend IM Bot 2025-03-20 17:14:30 +01:00
parent 43471438f1
commit edf213bfe2
11 changed files with 40 additions and 42 deletions

View File

@ -1,3 +1,4 @@
from sqlalchemy.orm import Session
from app.api.db.database import SessionLocal from app.api.db.database import SessionLocal
def get_db(): def get_db():

View File

@ -7,15 +7,7 @@ class ActivityTrackerMiddleware(BaseHTTPMiddleware):
start_time = time.time() start_time = time.time()
response = await call_next(request) response = await call_next(request)
process_time = time.time() - start_time process_time = time.time() - start_time
logger.info(f"{request.method} {request.url} - {process_time:.4f} seconds") request_method = request.method
return response request_url = str(request.url)
logger.info(f"{request_method} {request_url} processed in {process_time:.5f} seconds")
return response
The `dispatch` method first records the start time using `time.time()`. It then awaits the next middleware or the application itself by calling `call_next(request)`. After the response is received, the processing time is calculated by subtracting the start time from the current time. Finally, the request method, URL, and processing time are logged using `logger.info`.
from fastapi import FastAPI
from app.api.core.middleware.activity_tracker import ActivityTrackerMiddleware
app = FastAPI()
app.add_middleware(ActivityTrackerMiddleware)

View File

@ -6,6 +6,7 @@ SQLALCHEMY_DATABASE_URL = "sqlite:///./blog_app.db"
engine = create_engine( engine = create_engine(
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base() Base = declarative_base()

View File

@ -8,6 +8,6 @@ class And(Base):
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
title = Column(String) title = Column(String)
content = Column(String) content = Column(String)
author_id = Column(Integer, ForeignKey("users.id")) user_id = Column(Integer, ForeignKey("users.id"))
author = relationship("User", back_populates="ands") user = relationship("User", back_populates="ands")

View File

@ -1,4 +1,4 @@
from sqlalchemy import Column, Integer, String from sqlalchemy import Column, Integer, String, Boolean
from app.api.db.database import Base from app.api.db.database import Base
class User(Base): class User(Base):
@ -8,6 +8,5 @@ class User(Base):
username = Column(String, unique=True, index=True) username = Column(String, unique=True, index=True)
email = Column(String, unique=True, index=True) email = Column(String, unique=True, index=True)
password = Column(String) password = Column(String)
full_name = Column(String) is_active = Column(Boolean, default=True)
bio = Column(String) is_superuser = Column(Boolean, default=False)
profile_picture = Column(String)

View File

@ -1,11 +1,11 @@
from fastapi import APIRouter from fastapi import APIRouter
from .and import router as and_router
from .tags import router as tags_router from .tags import router as tags_router
from .user import router as user_router from .user import router as user_router
from .and import router as ands_router
router = APIRouter() router = APIRouter()
router.include_router(and_router, prefix="/ands", tags=["ands"])
router.include_router(tags_router, prefix="/tags", tags=["tags"]) router.include_router(tags_router, prefix="/tags", tags=["tags"])
router.include_router(user_router, prefix="/users", tags=["users"]) router.include_router(user_router, prefix="/users", tags=["users"])
router.include_router(ands_router, prefix="/ands", tags=["ands"])

View File

@ -2,9 +2,9 @@ from typing import List
from fastapi import APIRouter, Depends, HTTPException from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from app.api.core.dependencies.dependencies import get_db
from app.api.v1.models.and import And from app.api.v1.models.and import And
from app.api.v1.schemas.and import AndCreate, AndResponse from app.api.v1.schemas.and import AndCreate, AndResponse
from app.api.core.dependencies.dependencies import get_db
router = APIRouter() router = APIRouter()
@ -14,16 +14,16 @@ def read_ands(db: Session = Depends(get_db)):
return ands return ands
@router.post("/ands", response_model=AndResponse) @router.post("/ands", response_model=AndResponse)
def create_and(and_create: AndCreate, db: Session = Depends(get_db)): def create_and(and_data: AndCreate, db: Session = Depends(get_db)):
and_db = And(**and_create.dict()) and_instance = And(**and_data.dict())
db.add(and_db) db.add(and_instance)
db.commit() db.commit()
db.refresh(and_db) db.refresh(and_instance)
return and_db return and_instance
@router.get("/ands/{id}", response_model=AndResponse) @router.get("/ands/{id}", response_model=AndResponse)
def read_and(id: int, db: Session = Depends(get_db)): def read_and(id: int, db: Session = Depends(get_db)):
and_db = db.query(And).get(id) and_instance = db.query(And).get(id)
if not and_db: if not and_instance:
raise HTTPException(status_code=404, detail="And not found") raise HTTPException(status_code=404, detail="And not found")
return and_db return and_instance

View File

@ -1,13 +1,15 @@
from pydantic import BaseModel from pydantic import BaseModel
class AndBase(BaseModel): class AndBase(BaseModel):
pass title: str
body: str
class AndCreate(AndBase): class AndCreate(AndBase):
pass pass
class And(AndBase): class And(AndBase):
id: int id: int
owner_id: int
class Config: class Config:
orm_mode = True orm_mode = True

View File

@ -1,16 +1,21 @@
from pydantic import BaseModel, EmailStr from pydantic import BaseModel, EmailStr
from typing import Optional
class UserBase(BaseModel): class UserBase(BaseModel):
email: EmailStr email: Optional[EmailStr] = None
is_active: bool = True is_active: Optional[bool] = True
is_superuser: bool = False is_superuser: bool = False
full_name: str | None = None full_name: Optional[str] = None
class UserCreate(UserBase): class UserCreate(UserBase):
email: EmailStr
password: str password: str
class User(UserBase): class User(UserBase):
id: int id: int
is_active: bool
is_superuser: bool
full_name: str
class Config: class Config:
orm_mode = True orm_mode = True

View File

@ -8,10 +8,4 @@ app = FastAPI()
app.include_router(v1_router, prefix="/v1") app.include_router(v1_router, prefix="/v1")
app.add_middleware(ActivityTrackerMiddleware) app.add_middleware(ActivityTrackerMiddleware)
@app.on_event("startup") Base.metadata.create_all(bind=engine)
async def startup_event():
Base.metadata.create_all(bind=engine)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)

View File

@ -1 +1,5 @@
# No valid code generated fastapi
uvicorn
sqlalchemy
pydantic
loguru