Update generated backend for blog_app

This commit is contained in:
Backend IM Bot 2025-03-20 14:07:41 +01:00
parent 46e7d863f2
commit 43471438f1
10 changed files with 90 additions and 34 deletions

View File

@ -1,16 +1,21 @@
from typing import Callable, Awaitable
import time
from starlette.middleware.base import BaseHTTPMiddleware
from loguru import logger
from time import time
class ActivityTrackerMiddleware:
async def __call__(self, request: Request, call_next: Callable[[Request], Awaitable[Response]]) -> Response:
start_time = time()
request_method = request.method
request_url = str(request.url)
class ActivityTrackerMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time() - start_time
logger.info(f"{request_method} {request_url} - {process_time:.6f} seconds")
process_time = time.time() - start_time
logger.info(f"{request.method} {request.url} - {process_time:.4f} 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

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

View File

@ -0,0 +1,8 @@
from sqlalchemy import Column, Integer, String
from app.api.db.database import Base
class Tags(Base):
__tablename__ = "tags"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, unique=True, index=True)

View File

@ -1,13 +1,11 @@
from fastapi import APIRouter
from .users import router as users_router
from .auths import router as auths_router
from .comments import router as comments_router
from .posts import router as posts_router
from .and import router as and_router
from .tags import router as tags_router
from .user import router as user_router
router = APIRouter()
router.include_router(users_router, prefix="/users", tags=["users"])
router.include_router(auths_router, prefix="/auths", tags=["auths"])
router.include_router(comments_router, prefix="/comments", tags=["comments"])
router.include_router(posts_router, prefix="/posts", tags=["posts"])
router.include_router(and_router, prefix="/ands", tags=["ands"])
router.include_router(tags_router, prefix="/tags", tags=["tags"])
router.include_router(user_router, prefix="/users", tags=["users"])

View File

@ -23,7 +23,7 @@ def create_and(and_create: AndCreate, db: Session = Depends(get_db)):
@router.get("/ands/{id}", response_model=AndResponse)
def read_and(id: int, db: Session = Depends(get_db)):
and_db = db.query(And).filter(And.id == id).first()
and_db = db.query(And).get(id)
if not and_db:
raise HTTPException(status_code=404, detail="And not found")
return and_db

29
app/api/v1/routes/tags.py Normal file
View File

@ -0,0 +1,29 @@
from typing import List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.api.v1.models.tags import Tags
from app.api.v1.schemas.tags import TagsCreate, TagsResponse
from app.api.core.dependencies.dependencies import get_db
router = APIRouter()
@router.get("/tagss", response_model=List[TagsResponse])
def read_tagss(db: Session = Depends(get_db)):
tagss = db.query(Tags).all()
return tagss
@router.post("/tagss", response_model=TagsResponse)
def create_tags(tags: TagsCreate, db: Session = Depends(get_db)):
db_tags = Tags(**tags.dict())
db.add(db_tags)
db.commit()
db.refresh(db_tags)
return db_tags
@router.get("/tagss/{id}", response_model=TagsResponse)
def read_tags(id: int, db: Session = Depends(get_db)):
tags = db.query(Tags).get(id)
if not tags:
raise HTTPException(status_code=404, detail="Tags not found")
return tags

View File

@ -2,9 +2,9 @@ from typing import List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.api.core.dependencies import get_db
from app.api.v1.models.user import User
from app.api.v1.schemas.user import UserCreate, UserResponse
from app.api.core.dependencies.dependencies import get_db
router = APIRouter()

View File

@ -0,0 +1,15 @@
from typing import Optional
from pydantic import BaseModel
class TagsBase(BaseModel):
name: str
class TagsCreate(TagsBase):
pass
class Tags(TagsBase):
id: int
name: str
class Config:
orm_mode = True

View File

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

10
main.py
View File

@ -5,7 +5,13 @@ from app.api.core.middleware.activity_tracker import ActivityTrackerMiddleware
app = FastAPI()
Base.metadata.create_all(bind=engine)
app.include_router(v1_router, prefix="/v1")
app.add_middleware(ActivityTrackerMiddleware)
@app.on_event("startup")
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)