Update generated backend for blog_app
This commit is contained in:
parent
955f7541ae
commit
d1a7da24f8
13
app/api/core/dependencies/dependencies.py
Normal file
13
app/api/core/dependencies/dependencies.py
Normal file
@ -0,0 +1,13 @@
|
||||
from typing import Generator
|
||||
from sqlalchemy.orm import Session
|
||||
from app.api.db.database import SessionLocal
|
||||
def get_db() -> Generator[Session, None, None]:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
```
|
||||
This code defines a `get_db` function that returns a generator function. The generator function creates a new SQLAlchemy session using `SessionLocal` from `app.api.db.database` and yields the session. After the session is used, it is closed in the `finally` block.
|
||||
The function signature `get_db() -> Generator[Session, None, None]` specifies that the function returns a generator that yields a `Session` object and does not receive or return any values.
|
||||
This function is typically used as a dependency in FastAPI routes to provide a database session for querying and modifying data.
|
18
app/api/core/middleware/activity_tracker.py
Normal file
18
app/api/core/middleware/activity_tracker.py
Normal file
@ -0,0 +1,18 @@
|
||||
import time
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import Response
|
||||
from loguru import logger
|
||||
class ActivityTrackerMiddleware(BaseHTTPMiddleware):
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
start_time = time.time()
|
||||
request_method = request.method
|
||||
request_url = str(request.url)
|
||||
response: Response = await call_next(request)
|
||||
process_time = time.time() - start_time
|
||||
logger.info(f"{request_method} {request_url} - Process Time: {process_time:.6f} seconds")
|
||||
return response
|
||||
```
|
||||
This code defines an `ActivityTrackerMiddleware` class that inherits from `BaseHTTPMiddleware`. The `dispatch` method is overridden to log the request method, URL, and processing time for each incoming request.
|
||||
Here's a breakdown of the code:
|
||||
This middleware can be added to the FastAPI application by including it in the list of middleware instances when creating the application instance.
|
13
app/api/db/database.py
Normal file
13
app/api/db/database.py
Normal file
@ -0,0 +1,13 @@
|
||||
# app/api/db/database.py
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
SQLALCHEMY_DATABASE_URL = "sqlite:///./blog_app.db"
|
||||
engine = create_engine(
|
||||
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
|
||||
)
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
Base = declarative_base()
|
||||
```
|
||||
This code defines the necessary components for working with a SQLite database using SQLAlchemy in a FastAPI application named "blog_app".
|
||||
With this setup, you can define your database models by inheriting from `Base` and create database sessions using `SessionLocal`. The `engine` instance can be used for various database operations, such as creating tables or executing raw SQL queries.
|
11
app/api/v1/models/and.py
Normal file
11
app/api/v1/models/and.py
Normal file
@ -0,0 +1,11 @@
|
||||
from sqlalchemy import Column, Integer, String, ForeignKey
|
||||
from sqlalchemy.orm import relationship
|
||||
from app.api.db.database import Base
|
||||
class And(Base):
|
||||
__tablename__ = "ands"
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String, nullable=False)
|
||||
description = Column(String, nullable=True)
|
||||
# Relationships
|
||||
blog_id = Column(Integer, ForeignKey("blogs.id"))
|
||||
blog = relationship("Blog", back_populates="ands")
|
11
app/api/v1/models/comments.py
Normal file
11
app/api/v1/models/comments.py
Normal file
@ -0,0 +1,11 @@
|
||||
from sqlalchemy import Column, Integer, String, ForeignKey
|
||||
from sqlalchemy.orm import relationship
|
||||
from app.api.db.database import Base
|
||||
class Comments(Base):
|
||||
__tablename__ = "comments"
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
content = Column(String)
|
||||
post_id = Column(Integer, ForeignKey("posts.id"))
|
||||
user_id = Column(Integer, ForeignKey("users.id"))
|
||||
post = relationship("Post", back_populates="comments")
|
||||
user = relationship("User", back_populates="comments")
|
11
app/api/v1/models/posts.py
Normal file
11
app/api/v1/models/posts.py
Normal file
@ -0,0 +1,11 @@
|
||||
from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey
|
||||
from sqlalchemy.orm import relationship
|
||||
from app.api.db.database import Base
|
||||
class Posts(Base):
|
||||
__tablename__ = "posts"
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
title = Column(String)
|
||||
content = Column(Text)
|
||||
published = Column(DateTime)
|
||||
user_id = Column(Integer, ForeignKey("users.id"))
|
||||
user = relationship("Users", back_populates="posts")
|
11
app/api/v1/models/user.py
Normal file
11
app/api/v1/models/user.py
Normal file
@ -0,0 +1,11 @@
|
||||
# app/api/v1/models/user.py
|
||||
from sqlalchemy import Column, Integer, String, Boolean
|
||||
from app.api.db.database import Base
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
username = Column(String, unique=True, index=True)
|
||||
email = Column(String, unique=True, index=True)
|
||||
password = Column(String)
|
||||
is_active = Column(Boolean, default=True)
|
||||
is_admin = Column(Boolean, default=False)
|
@ -0,0 +1,10 @@
|
||||
from fastapi import APIRouter
|
||||
from .posts import router as posts_router
|
||||
from .comments import router as comments_router
|
||||
from .user import router as user_router
|
||||
from .and import router as and_router
|
||||
router = APIRouter()
|
||||
router.include_router(posts_router, prefix="/posts", tags=["posts"])
|
||||
router.include_router(comments_router, prefix="/comments", tags=["comments"])
|
||||
router.include_router(user_router, prefix="/users", tags=["users"])
|
||||
router.include_router(and_router, prefix="/and", tags=["and"])
|
24
app/api/v1/routes/and.py
Normal file
24
app/api/v1/routes/and.py
Normal file
@ -0,0 +1,24 @@
|
||||
from typing import List
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
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.schemas.and import AndCreate, AndRead
|
||||
router = APIRouter()
|
||||
@router.get("/ands", response_model=List[AndRead])
|
||||
def read_ands(db: Session = Depends(get_db)):
|
||||
ands = db.query(And).all()
|
||||
return ands
|
||||
@router.post("/ands", response_model=AndRead)
|
||||
def create_and(and_data: AndCreate, db: Session = Depends(get_db)):
|
||||
and_obj = And(**and_data.dict())
|
||||
db.add(and_obj)
|
||||
db.commit()
|
||||
db.refresh(and_obj)
|
||||
return and_obj
|
||||
@router.get("/ands/{id}", response_model=AndRead)
|
||||
def read_and(id: int, db: Session = Depends(get_db)):
|
||||
and_obj = db.query(And).get(id)
|
||||
if not and_obj:
|
||||
raise HTTPException(status_code=404, detail="And not found")
|
||||
return and_obj
|
24
app/api/v1/routes/comments.py
Normal file
24
app/api/v1/routes/comments.py
Normal file
@ -0,0 +1,24 @@
|
||||
from typing import List
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from app.api.v1.models.comments import Comments
|
||||
from app.api.v1.schemas.comments import CommentsCreate, CommentsResponse
|
||||
from app.api.core.dependencies.dependencies import get_db
|
||||
router = APIRouter()
|
||||
@router.get("/commentss", response_model=List[CommentsResponse])
|
||||
def read_commentss(db: Session = Depends(get_db)):
|
||||
commentss = db.query(Comments).all()
|
||||
return commentss
|
||||
@router.post("/commentss", response_model=CommentsResponse)
|
||||
def create_comments(comments: CommentsCreate, db: Session = Depends(get_db)):
|
||||
db_comments = Comments(**comments.dict())
|
||||
db.add(db_comments)
|
||||
db.commit()
|
||||
db.refresh(db_comments)
|
||||
return db_comments
|
||||
@router.get("/commentss/{id}", response_model=CommentsResponse)
|
||||
def read_comments(id: int, db: Session = Depends(get_db)):
|
||||
db_comments = db.query(Comments).get(id)
|
||||
if not db_comments:
|
||||
raise HTTPException(status_code=404, detail="Comments not found")
|
||||
return db_comments
|
24
app/api/v1/routes/posts.py
Normal file
24
app/api/v1/routes/posts.py
Normal file
@ -0,0 +1,24 @@
|
||||
from typing import List
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from app.api.v1.models.posts import Posts
|
||||
from app.api.v1.schemas.posts import PostsCreate, PostsResponse
|
||||
from app.api.core.dependencies.dependencies import get_db
|
||||
router = APIRouter()
|
||||
@router.get("/postss", response_model=List[PostsResponse])
|
||||
def read_postss(db: Session = Depends(get_db)):
|
||||
postss = db.query(Posts).all()
|
||||
return postss
|
||||
@router.post("/postss", response_model=PostsResponse)
|
||||
def create_posts(posts: PostsCreate, db: Session = Depends(get_db)):
|
||||
db_posts = Posts(**posts.dict())
|
||||
db.add(db_posts)
|
||||
db.commit()
|
||||
db.refresh(db_posts)
|
||||
return db_posts
|
||||
@router.get("/postss/{id}", response_model=PostsResponse)
|
||||
def read_posts(id: int, db: Session = Depends(get_db)):
|
||||
posts = db.query(Posts).get(id)
|
||||
if not posts:
|
||||
raise HTTPException(status_code=404, detail="Posts not found")
|
||||
return posts
|
24
app/api/v1/routes/user.py
Normal file
24
app/api/v1/routes/user.py
Normal file
@ -0,0 +1,24 @@
|
||||
from typing import List
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from app.api.v1.models.user import User
|
||||
from app.api.v1.schemas.user import UserCreate, UserRead
|
||||
from app.api.core.dependencies.dependencies import get_db
|
||||
router = APIRouter()
|
||||
@router.get("/users", response_model=List[UserRead])
|
||||
def read_users(db: Session = Depends(get_db)):
|
||||
users = db.query(User).all()
|
||||
return users
|
||||
@router.post("/users", response_model=UserRead)
|
||||
def create_user(user: UserCreate, db: Session = Depends(get_db)):
|
||||
db_user = User(**user.dict())
|
||||
db.add(db_user)
|
||||
db.commit()
|
||||
db.refresh(db_user)
|
||||
return db_user
|
||||
@router.get("/users/{user_id}", response_model=UserRead)
|
||||
def read_user(user_id: int, db: Session = Depends(get_db)):
|
||||
db_user = db.query(User).filter(User.id == user_id).first()
|
||||
if not db_user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
return db_user
|
13
app/api/v1/schemas/and.py
Normal file
13
app/api/v1/schemas/and.py
Normal file
@ -0,0 +1,13 @@
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel
|
||||
# AndCreate Schema
|
||||
class AndCreate(BaseModel):
|
||||
title: str
|
||||
body: str
|
||||
# And Schema
|
||||
class And(AndCreate):
|
||||
id: int
|
||||
is_published: bool
|
||||
rating: Optional[int] = None
|
||||
class Config:
|
||||
orm_mode = True
|
14
app/api/v1/schemas/comments.py
Normal file
14
app/api/v1/schemas/comments.py
Normal file
@ -0,0 +1,14 @@
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel
|
||||
class CommentsBase(BaseModel):
|
||||
body: str
|
||||
post_id: int
|
||||
class CommentsCreate(CommentsBase):
|
||||
pass
|
||||
class Comments(CommentsBase):
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: Optional[datetime] = None
|
||||
class Config:
|
||||
orm_mode = True
|
18
app/api/v1/schemas/posts.py
Normal file
18
app/api/v1/schemas/posts.py
Normal file
@ -0,0 +1,18 @@
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel
|
||||
class PostsCreate(BaseModel):
|
||||
title: str
|
||||
content: str
|
||||
published: bool = True
|
||||
author_id: int
|
||||
class Posts(BaseModel):
|
||||
id: int
|
||||
title: str
|
||||
content: str
|
||||
published: bool
|
||||
created_at: datetime
|
||||
updated_at: Optional[datetime] = None
|
||||
author_id: int
|
||||
class Config:
|
||||
orm_mode = True
|
16
app/api/v1/schemas/user.py
Normal file
16
app/api/v1/schemas/user.py
Normal file
@ -0,0 +1,16 @@
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel, EmailStr
|
||||
# User Pydantic models
|
||||
class UserBase(BaseModel):
|
||||
email: Optional[EmailStr] = None
|
||||
is_active: Optional[bool] = True
|
||||
is_superuser: bool = False
|
||||
full_name: Optional[str] = None
|
||||
class UserCreate(UserBase):
|
||||
email: EmailStr
|
||||
password: str
|
||||
class User(UserBase):
|
||||
id: int
|
||||
disabled: bool = False
|
||||
class Config:
|
||||
orm_mode = True
|
16
main.py
16
main.py
@ -1,7 +1,11 @@
|
||||
from fastapi import FastAPI
|
||||
|
||||
app = FastAPI(title="Generated Backend")
|
||||
|
||||
@app.get("/")
|
||||
def read_root():
|
||||
return {"message": "Welcome to the generated backend"}
|
||||
from app.api.db.database import Base, engine
|
||||
from app.api.v1.routes import router as v1_router
|
||||
from app.api.core.middleware.activity_tracker import ActivityTrackerMiddleware
|
||||
app = FastAPI()
|
||||
# Create tables
|
||||
Base.metadata.create_all(bind=engine)
|
||||
# Include v1 router
|
||||
app.include_router(v1_router, prefix="/v1")
|
||||
# Add middleware
|
||||
app.add_middleware(ActivityTrackerMiddleware)
|
Loading…
x
Reference in New Issue
Block a user