Update generated backend for blog_app
This commit is contained in:
parent
37ed2d4bc6
commit
a173ca5925
9
app/api/core/dependencies/dependencies.py
Normal file
9
app/api/core/dependencies/dependencies.py
Normal file
@ -0,0 +1,9 @@
|
||||
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()
|
26
app/api/core/middleware/activity_tracker.py
Normal file
26
app/api/core/middleware/activity_tracker.py
Normal file
@ -0,0 +1,26 @@
|
||||
import time
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import Response
|
||||
import logging
|
||||
logger = logging.getLogger(__name__)
|
||||
class ActivityTrackerMiddleware(BaseHTTPMiddleware):
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
start_time = time.time()
|
||||
response = await call_next(request)
|
||||
process_time = time.time() - start_time
|
||||
logger.info(
|
||||
f"Request: {request.method} {request.url.path} - Processing Time: {process_time:.6f} seconds"
|
||||
)
|
||||
return response
|
||||
```
|
||||
This code defines an `ActivityTrackerMiddleware` class that inherits from `BaseHTTPMiddleware` from the Starlette library. The `dispatch` method is overridden to log the request method, URL path, 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. For example:
|
||||
```python
|
||||
from fastapi import FastAPI
|
||||
from app.api.core.middleware.activity_tracker import ActivityTrackerMiddleware
|
||||
app = FastAPI()
|
||||
app.add_middleware(ActivityTrackerMiddleware)
|
||||
```
|
||||
With this middleware in place, each incoming request will be logged with its method, URL path, and processing time.
|
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 interacting with a SQLite database using SQLAlchemy in a FastAPI application named "blog_app".
|
||||
This file should be placed in the `app/api/db/` directory of the FastAPI project. Other parts of the application can import and use these components to interact with the database.
|
12
app/api/v1/models/and.py
Normal file
12
app/api/v1/models/and.py
Normal file
@ -0,0 +1,12 @@
|
||||
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)
|
||||
title = Column(String)
|
||||
content = Column(String)
|
||||
post_id = Column(Integer, ForeignKey("posts.id"))
|
||||
post = relationship("Post", back_populates="ands")
|
||||
author_id = Column(Integer, ForeignKey("users.id"))
|
||||
author = relationship("User", 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)
|
||||
text = Column(String)
|
||||
post_id = Column(Integer, ForeignKey("posts.id"))
|
||||
user_id = Column(Integer, ForeignKey("users.id"))
|
||||
post = relationship("Posts", back_populates="comments")
|
||||
user = relationship("Users", back_populates="comments")
|
10
app/api/v1/models/posts.py
Normal file
10
app/api/v1/models/posts.py
Normal file
@ -0,0 +1,10 @@
|
||||
from sqlalchemy import Column, Integer, String, Text, 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)
|
||||
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)
|
||||
hashed_password = Column(String)
|
||||
is_active = Column(Boolean, default=True)
|
||||
is_superuser = 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 ands_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(ands_router, prefix="/ands", tags=["ands"])
|
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.v1.models.and import And
|
||||
from app.api.v1.schemas.and import AndCreate, AndResponse
|
||||
from app.api.core.dependencies.dependencies import get_db
|
||||
router = APIRouter()
|
||||
@router.get("/ands", response_model=List[AndResponse])
|
||||
def read_ands(db: Session = Depends(get_db)):
|
||||
ands = db.query(And).all()
|
||||
return ands
|
||||
@router.post("/ands", response_model=AndResponse)
|
||||
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=AndResponse)
|
||||
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 Comment
|
||||
from app.api.v1.schemas.comments import CommentCreate, CommentResponse
|
||||
from app.api.core.dependencies.dependencies import get_db
|
||||
router = APIRouter()
|
||||
@router.get("/commentss", response_model=List[CommentResponse])
|
||||
def read_comments(db: Session = Depends(get_db)):
|
||||
comments = db.query(Comment).all()
|
||||
return comments
|
||||
@router.post("/commentss", response_model=CommentResponse)
|
||||
def create_comment(comment: CommentCreate, db: Session = Depends(get_db)):
|
||||
db_comment = Comment(**comment.dict())
|
||||
db.add(db_comment)
|
||||
db.commit()
|
||||
db.refresh(db_comment)
|
||||
return db_comment
|
||||
@router.get("/commentss/{id}", response_model=CommentResponse)
|
||||
def read_comment(id: int, db: Session = Depends(get_db)):
|
||||
comment = db.query(Comment).get(id)
|
||||
if not comment:
|
||||
raise HTTPException(status_code=404, detail="Comment not found")
|
||||
return comment
|
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).get(user_id)
|
||||
if not db_user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
return db_user
|
11
app/api/v1/schemas/and.py
Normal file
11
app/api/v1/schemas/and.py
Normal file
@ -0,0 +1,11 @@
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel
|
||||
# And Pydantic Schema
|
||||
class AndBase(BaseModel):
|
||||
pass
|
||||
class AndCreate(AndBase):
|
||||
pass
|
||||
class And(AndBase):
|
||||
id: int
|
||||
class Config:
|
||||
orm_mode = True
|
16
app/api/v1/schemas/comments.py
Normal file
16
app/api/v1/schemas/comments.py
Normal file
@ -0,0 +1,16 @@
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel
|
||||
from datetime import datetime
|
||||
class CommentsCreate(BaseModel):
|
||||
body: str
|
||||
post_id: int
|
||||
user_id: int
|
||||
class Comments(BaseModel):
|
||||
id: int
|
||||
body: str
|
||||
created_at: datetime
|
||||
updated_at: Optional[datetime] = None
|
||||
post_id: int
|
||||
user_id: int
|
||||
class Config:
|
||||
orm_mode = True
|
16
app/api/v1/schemas/posts.py
Normal file
16
app/api/v1/schemas/posts.py
Normal file
@ -0,0 +1,16 @@
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel
|
||||
# Posts schema
|
||||
class PostsCreate(BaseModel):
|
||||
title: str
|
||||
content: str
|
||||
published: bool = True
|
||||
class Posts(BaseModel):
|
||||
id: int
|
||||
title: str
|
||||
content: str
|
||||
published: bool
|
||||
created_at: Optional[str] = None
|
||||
updated_at: Optional[str] = None
|
||||
class Config:
|
||||
orm_mode = True
|
18
app/api/v1/schemas/user.py
Normal file
18
app/api/v1/schemas/user.py
Normal file
@ -0,0 +1,18 @@
|
||||
from typing import Optional
|
||||
from pydantic import BaseModel, EmailStr
|
||||
# User Schema
|
||||
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
|
||||
is_active: bool
|
||||
is_superuser: bool
|
||||
full_name: str
|
||||
class Config:
|
||||
orm_mode = True
|
18
main.py
18
main.py
@ -1,7 +1,13 @@
|
||||
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 engine, Base
|
||||
from app.api.v1.routes import router as v1_router
|
||||
from app.api.core.middleware.activity_tracker import ActivityTrackerMiddleware
|
||||
app = FastAPI()
|
||||
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("main:app", host="0.0.0.0", port=8000, reload=True)
|
Loading…
x
Reference in New Issue
Block a user