Update generated backend for blog_app with entities: posts, comments, tags, user

This commit is contained in:
Idris Abdurrahman 2025-03-21 09:12:16 +01:00
parent 12cbe312f1
commit 186e46d24f
18 changed files with 687 additions and 8 deletions

View File

@ -0,0 +1,25 @@
Here's the `dependencies.py` file for the `app/api/core/dependencies/` directory in the `blog_app_igblf` FastAPI backend project:
from databases import Database
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from app.core.settings import settings
engine = create_engine(
settings.DATABASE_URL, connect_args={"check_same_thread": False}
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
This `dependencies.py` file contains the following components:

View File

@ -0,0 +1,63 @@
Here's an example of an `activity_tracker.py` file that defines middleware for a FastAPI backend named 'blog_app' using SQLite and SQLAlchemy:
from datetime import datetime
from typing import Callable, Awaitable
from sqlalchemy.orm import Session
from fastapi import Request, Response
from app.db.session import get_db
from app.db.models import ActivityLog
async def log_activity(request: Request, call_next: Callable[[Request], Awaitable[Response]]) -> Response:
start_time = datetime.now()
response = await call_next(request)
process_time = (datetime.now() - start_time).total_seconds() * 1000
try:
db: Session = next(get_db())
activity_log = ActivityLog(
path=str(request.url.path),
method=request.method,
status_code=response.status_code,
process_time=process_time,
ip_address=request.client.host,
user_agent=request.headers.get("User-Agent"),
)
db.add(activity_log)
db.commit()
except Exception as e:
print(f"Error logging activity: {e}")
finally:
db.close()
return response
Here's a breakdown of the code:
3. Inside the `log_activity` function, the start time is recorded using `datetime.now()`.
8. The `ActivityLog` instance is added to the database session using `db.add(activity_log)`, and the changes are committed using `db.commit()`.
9. If an exception occurs during the database operation, an error message is printed (you may want to implement more robust error handling).
10. Finally, the database session is closed using `db.close()`.
To use this middleware in your FastAPI application, you need to include it in the middleware stack. You can do this by adding the following code to your `main.py` file or wherever you configure your FastAPI application:
from fastapi import FastAPI
from app.api.core.middleware.activity_tracker import log_activity
app = FastAPI()
app.middleware("http")(log_activity)
Note: This example assumes that you have already defined the `ActivityLog` model in your `app.db.models` module and set up the necessary database connections and session management.

26
app/api/db/database.py Normal file
View File

@ -0,0 +1,26 @@
Sure, here's the `database.py` file for the `app/api/db/` directory, which configures SQLite with `blog_app.db` using SQLAlchemy:
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()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
Here's a breakdown of the code:
1. We import the necessary modules from SQLAlchemy: `create_engine`, `declarative_base`, and `sessionmaker`.
2. We define the `SQLALCHEMY_DATABASE_URL` as a string with the SQLite database file path (`blog_app.db`).

View File

@ -0,0 +1,32 @@
Here's the `comments.py` file for the `app/api/v1/models/` directory in the `blog_app_igblf` FastAPI backend:
from sqlalchemy import Column, ForeignKey, Integer, String, Text
from sqlalchemy.orm import relationship
from app.db.base_class import Base
class Comment(Base):
__tablename__ = "comments"
id = Column(Integer, primary_key=True, index=True)
text = Column(Text, nullable=False)
user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
post_id = Column(Integer, ForeignKey("posts.id"), nullable=False)
user = relationship("User", back_populates="comments")
post = relationship("Post", back_populates="comments")
def __repr__(self):
return f"Comment(id={self.id}, text='{self.text[:20]}...', user_id={self.user_id}, post_id={self.post_id})"
Explanation:
1. We import the necessary modules from SQLAlchemy: `Column`, `ForeignKey`, `Integer`, `String`, `Text`, and `relationship`.
5. We define the columns for the `Comment` model:
- `id`: an integer primary key and index column.
- `text`: a text column for the comment content, which is required (`nullable=False`).
- `user_id`: an integer foreign key column referring to the `users` table, which is required (`nullable=False`).
- `post_id`: an integer foreign key column referring to the `posts` table, which is required (`nullable=False`).
6. We define the relationships between the `Comment` model and the `User` and `Post` models using the `relationship` function from SQLAlchemy:
- `user`: a one-to-many relationship with the `User` model, using the `back_populates` parameter to enable bi-directional access.
- `post`: a one-to-many relationship with the `Post` model, using the `back_populates` parameter to enable bi-directional access.

View File

@ -0,0 +1,37 @@
Here's the `posts.py` file for the `app/api/v1/models/` directory in the `blog_app_igblf` FastAPI backend project, defining a SQLAlchemy model for posts:
from sqlalchemy import Column, Integer, String, Text, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.sql.sqltypes import TIMESTAMP
from sqlalchemy.sql import func
from app.db import Base
class Post(Base):
__tablename__ = "posts"
id = Column(Integer, primary_key=True, index=True)
title = Column(String, nullable=False)
content = Column(Text, nullable=False)
created_at = Column(TIMESTAMP, server_default=func.now())
updated_at = Column(TIMESTAMP, server_default=func.now(), onupdate=func.now())
user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
user = relationship("User", back_populates="posts")
def __repr__(self):
return f"Post(id={self.id}, title='{self.title}', content='{self.content[:20]}...')"
Explanation:
3. The following columns are defined for the `Post` model:
- `id`: An auto-incrementing primary key column of type `Integer`.
- `title`: A non-nullable `String` column for the post title.
- `content`: A non-nullable `Text` column for the post content.
- `created_at`: A `TIMESTAMP` column that defaults to the current time when a new row is inserted.
- `updated_at`: A `TIMESTAMP` column that defaults to the current time when a new row is inserted and updates to the current time whenever the row is updated.
- `user_id`: A non-nullable `Integer` column that acts as a foreign key referencing the `id` column of the `users` table.
4. The `user` attribute is defined as a SQLAlchemy relationship to the `User` model, which is assumed to be defined in another file (e.g., `app/api/v1/models/users.py`). The `back_populates` parameter specifies the name of the attribute on the `User` model that should be used for the reverse relationship.
Note: This code assumes that you have already set up the necessary database connection and defined the `Base` class in the `app/db.py` file. Additionally, you'll need to create the `users` table and define the `User` model in a separate file (e.g., `app/api/v1/models/users.py`) to establish the relationship between posts and users.

22
app/api/v1/models/tags.py Normal file
View File

@ -0,0 +1,22 @@
Here's the `tags.py` file that defines a SQLAlchemy model for tags, located in the `app/api/v1/models/` directory:
from sqlalchemy import Column, Integer, String
from app.db import Base
class Tag(Base):
__tablename__ = "tags"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, unique=True, index=True)
def __repr__(self):
return f"Tag(id={self.id}, name='{self.name}')"
The `Tag` model has the following attributes:
This file assumes that you have already set up the necessary imports and dependencies for SQLAlchemy and the database connection in your FastAPI project. If you haven't done so, you'll need to add the required imports and configurations in the appropriate files (e.g., `app/db.py`, `app/main.py`).
Additionally, you'll need to create the `tags` table in your SQLite database using the `Base.metadata.create_all(engine)` method, where `engine` is the database engine instance you've configured in your project.

25
app/api/v1/models/user.py Normal file
View File

@ -0,0 +1,25 @@
Here's the `user.py` file for the `app/api/v1/models/` directory in the `blog_app_igblf` FastAPI backend:
from sqlalchemy import Column, Integer, String, Boolean
from app.db 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)
def __repr__(self):
return f"User(id={self.id}, username='{self.username}', email='{self.email}')"
This file defines a SQLAlchemy model named `User` that inherits from the `Base` class (which should be defined in `app/db.py`). The `User` model has the following columns:
- `is_active`: A boolean indicating whether the user is active or not (default is `True`).
- `is_superuser`: A boolean indicating whether the user is a superuser or not (default is `False`).
Make sure to import the necessary modules (`sqlalchemy` and `app.db`) at the top of the file. Also, ensure that the `Base` class is properly defined in `app/db.py` and that the SQLite database is correctly configured and initialized in your FastAPI application.

View File

@ -0,0 +1,22 @@
Here's the `__init__.py` file for the `app/api/v1/routes/` directory, which aggregates the routers for posts, comments, tags, and user:
from fastapi import APIRouter
from .posts import router as posts_router
from .comments import router as comments_router
from .tags import router as tags_router
from .user import router as user_router
router = APIRouter()
router.include_router(posts_router, prefix="/posts", tags=["posts"])
router.include_router(comments_router, prefix="/comments", tags=["comments"])
router.include_router(tags_router, prefix="/tags", tags=["tags"])
router.include_router(user_router, prefix="/user", tags=["user"])
Explanation:
- `prefix` is used to define the base URL path for each router.
- `tags` is used to group related routes in the automatically generated API documentation.
Note: Make sure that the `posts.py`, `comments.py`, `tags.py`, and `user.py` files exist in the same directory (`app/api/v1/routes/`) and contain the respective router definitions.

View File

@ -0,0 +1,61 @@
from typing import List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.db import get_db
from app.models.comment import Comment
from app.schemas.comment import CommentCreate, CommentResponse
router = APIRouter()
@router.post("/comments", response_model=CommentResponse, status_code=201)
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("/comments", response_model=List[CommentResponse])
def get_all_comments(db: Session = Depends(get_db)):
comments = db.query(Comment).all()
return comments
@router.get("/comments/{comment_id}", response_model=CommentResponse)
def get_comment(comment_id: int, db: Session = Depends(get_db)):
comment = db.query(Comment).filter(Comment.id == comment_id).first()
if not comment:
raise HTTPException(status_code=404, detail="Comment not found")
return comment
@router.put("/comments/{comment_id}", response_model=CommentResponse)
def update_comment(comment_id: int, comment: CommentCreate, db: Session = Depends(get_db)):
db_comment = db.query(Comment).filter(Comment.id == comment_id).first()
if not db_comment:
raise HTTPException(status_code=404, detail="Comment not found")
update_data = comment.dict(exclude_unset=True)
for key, value in update_data.items():
setattr(db_comment, key, value)
db.commit()
db.refresh(db_comment)
return db_comment
@router.delete("/comments/{comment_id}", status_code=204)
def delete_comment(comment_id: int, db: Session = Depends(get_db)):
comment = db.query(Comment).filter(Comment.id == comment_id).first()
if not comment:
raise HTTPException(status_code=404, detail="Comment not found")
db.delete(comment)
db.commit()
return None
This code defines a set of CRUD (Create, Read, Update, Delete) endpoints for comments in a FastAPI application. Here's a breakdown of the functionality:
1. `create_comment` endpoint: Accepts a `CommentCreate` Pydantic model and creates a new comment in the database.
2. `get_all_comments` endpoint: Retrieves a list of all comments from the database.
3. `get_comment` endpoint: Retrieves a single comment by its ID. If the comment is not found, it raises an `HTTPException` with a 404 status code.
4. `update_comment` endpoint: Updates an existing comment by its ID. If the comment is not found, it raises an `HTTPException` with a 404 status code.
5. `delete_comment` endpoint: Deletes a comment by its ID. If the comment is not found, it raises an `HTTPException` with a 404 status code.
Note: You will need to import the required models and schemas in your application and ensure that the database connection is properly configured.

View File

@ -0,0 +1,58 @@
from typing import List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.db import get_db
from app.models import Post
from app.schemas import PostCreate, PostResponse
router = APIRouter()
@router.post("/posts", response_model=PostResponse, status_code=status.HTTP_201_CREATED)
def create_post(post: PostCreate, db: Session = Depends(get_db)):
new_post = Post(**post.dict())
db.add(new_post)
db.commit()
db.refresh(new_post)
return new_post
@router.get("/posts", response_model=List[PostResponse])
def get_all_posts(db: Session = Depends(get_db)):
posts = db.query(Post).all()
return posts
@router.get("/posts/{post_id}", response_model=PostResponse)
def get_post(post_id: int, db: Session = Depends(get_db)):
post = db.query(Post).filter(Post.id == post_id).first()
if not post:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Post not found")
return post
@router.put("/posts/{post_id}", response_model=PostResponse)
def update_post(post_id: int, post: PostCreate, db: Session = Depends(get_db)):
db_post = db.query(Post).filter(Post.id == post_id).first()
if not db_post:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Post not found")
update_data = post.dict(exclude_unset=True)
for key, value in update_data.items():
setattr(db_post, key, value)
db.commit()
db.refresh(db_post)
return db_post
@router.delete("/posts/{post_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_post(post_id: int, db: Session = Depends(get_db)):
post = db.query(Post).filter(Post.id == post_id).first()
if not post:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Post not found")
db.delete(post)
db.commit()
return
This file defines the following endpoints:
The endpoints use SQLAlchemy models (`Post`) and Pydantic schemas (`PostCreate`, `PostResponse`) for data validation and serialization. The `get_db` dependency function from `app.db` is used to get a database session.
Note: You'll need to define the `Post` model in `app/models.py` and the `PostCreate` and `PostResponse` schemas in `app/schemas.py` for this code to work properly.

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

@ -0,0 +1,57 @@
from typing import List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.db.session import get_db
from app.models.tag import Tag
from app.schemas.tag import TagCreate, TagUpdate, TagOut
router = APIRouter()
@router.post("/tags", response_model=TagOut, status_code=201)
def create_tag(tag: TagCreate, db: Session = Depends(get_db)):
db_tag = Tag(**tag.dict())
db.add(db_tag)
db.commit()
db.refresh(db_tag)
return db_tag
@router.get("/tags", response_model=List[TagOut])
def read_tags(db: Session = Depends(get_db)):
tags = db.query(Tag).all()
return tags
@router.get("/tags/{tag_id}", response_model=TagOut)
def read_tag(tag_id: int, db: Session = Depends(get_db)):
db_tag = db.query(Tag).filter(Tag.id == tag_id).first()
if not db_tag:
raise HTTPException(status_code=404, detail="Tag not found")
return db_tag
@router.put("/tags/{tag_id}", response_model=TagOut)
def update_tag(tag_id: int, tag: TagUpdate, db: Session = Depends(get_db)):
db_tag = db.query(Tag).filter(Tag.id == tag_id).first()
if not db_tag:
raise HTTPException(status_code=404, detail="Tag not found")
update_data = tag.dict(exclude_unset=True)
for key, value in update_data.items():
setattr(db_tag, key, value)
db.add(db_tag)
db.commit()
db.refresh(db_tag)
return db_tag
@router.delete("/tags/{tag_id}", status_code=204)
def delete_tag(tag_id: int, db: Session = Depends(get_db)):
db_tag = db.query(Tag).filter(Tag.id == tag_id).first()
if not db_tag:
raise HTTPException(status_code=404, detail="Tag not found")
db.delete(db_tag)
db.commit()
return None
This file defines the following endpoints:
Note that you'll need to import the required models and schemas in this file, and define them in their respective modules (`app/models/tag.py` and `app/schemas/tag.py`).

55
app/api/v1/routes/user.py Normal file
View File

@ -0,0 +1,55 @@
Here's the `user.py` file with CRUD endpoints for the `User` model:
from typing import List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.db import get_db
from app.models import User as UserModel
from app.schemas import User, UserCreate, UserUpdate
router = APIRouter()
@router.get("/users/", response_model=List[User])
def read_users(db: Session = Depends(get_db)):
users = db.query(UserModel).all()
return users
@router.get("/users/{user_id}", response_model=User)
def read_user(user_id: int, db: Session = Depends(get_db)):
user = db.query(UserModel).get(user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
@router.post("/users/", response_model=User)
def create_user(user: UserCreate, db: Session = Depends(get_db)):
db_user = UserModel(**user.dict())
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
@router.put("/users/{user_id}", response_model=User)
def update_user(user_id: int, user: UserUpdate, db: Session = Depends(get_db)):
db_user = db.query(UserModel).get(user_id)
if not db_user:
raise HTTPException(status_code=404, detail="User not found")
update_data = user.dict(exclude_unset=True)
for key, value in update_data.items():
setattr(db_user, key, value)
db.commit()
db.refresh(db_user)
return db_user
@router.delete("/users/{user_id}")
def delete_user(user_id: int, db: Session = Depends(get_db)):
db_user = db.query(UserModel).get(user_id)
if not db_user:
raise HTTPException(status_code=404, detail="User not found")
db.delete(db_user)
db.commit()
return {"message": "User deleted successfully"}
This file defines the following endpoints:

View File

@ -0,0 +1,40 @@
Here's the `comments.py` file with Pydantic schemas for comments, following the FastAPI project structure with SQLite and SQLAlchemy:
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field
class CommentBase(BaseModel):
content: str = Field(..., min_length=1, max_length=500)
class CommentCreate(CommentBase):
pass
class CommentUpdate(CommentBase):
pass
class CommentInDBBase(CommentBase):
id: int
post_id: int
created_at: datetime
updated_at: Optional[datetime] = None
class Config:
orm_mode = True
class Comment(CommentInDBBase):
pass
class CommentInDB(CommentInDBBase):
pass
Explanation:
1. We import the necessary modules: `datetime` for working with dates and times, `typing` for type hints, and `pydantic` for defining data models.
5. `CommentInDBBase` inherits from `CommentBase` and adds additional fields for database-related information: `id` (comment ID), `post_id` (ID of the associated post), `created_at` (creation timestamp), and `updated_at` (optional update timestamp). The `Config` class is used to enable the `orm_mode`, which allows Pydantic to work with SQLAlchemy models.

View File

@ -0,0 +1,42 @@
from typing import Optional
from pydantic import BaseModel
from datetime import datetime
class PostBase(BaseModel):
title: str
content: str
class PostCreate(PostBase):
pass
class PostUpdate(PostBase):
pass
class PostInDBBase(PostBase):
id: int
created_at: datetime
updated_at: Optional[datetime] = None
class Config:
orm_mode = True
class Post(PostInDBBase):
pass
class PostList(BaseModel):
__root__: list[Post]
Explanation:
1. We import the necessary modules: `typing` for type hints, `pydantic` for defining data models, and `datetime` for handling date and time.
2. `PostBase` is a base Pydantic model that defines the common fields for a post: `title` and `content`.
5. `PostInDBBase` inherits from `PostBase` and adds additional fields: `id` (post ID), `created_at` (creation timestamp), and `updated_at` (optional update timestamp). The `Config` class is set to `orm_mode = True` to allow Pydantic to work with SQLAlchemy models.
Make sure to install the required dependencies (`pydantic` and `sqlalchemy`) in your project environment if you haven't already done so.

View File

@ -0,0 +1,30 @@
Here's the `tags.py` file with Pydantic schemas for tags, located in the `app/api/v1/schemas/` directory:
from typing import Optional
from pydantic import BaseModel
class TagBase(BaseModel):
name: str
class TagCreate(TagBase):
pass
class TagUpdate(TagBase):
pass
class TagInDBBase(TagBase):
id: int
name: str
class Config:
orm_mode = True
class Tag(TagInDBBase):
pass
class TagInDB(TagInDBBase):
pass
Explanation:
1. We import the necessary modules: `typing` for type hints and `pydantic` for defining data models.

View File

@ -0,0 +1,42 @@
Here's the `user.py` file with Pydantic schemas for the user model in the `app/api/v1/schemas/` directory:
from typing import Optional
from pydantic import BaseModel, EmailStr
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 UserUpdate(UserBase):
password: Optional[str] = None
class UserInDBBase(UserBase):
id: Optional[int] = None
class Config:
orm_mode = True
class User(UserInDBBase):
pass
class UserInDB(UserInDBBase):
hashed_password: str
Explanation:
1. We import the necessary modules: `typing` for type hints, and `pydantic` for defining data models.
Note: This file assumes that you have the necessary dependencies installed, such as `pydantic` and `email-validator` (for `EmailStr`). Additionally, you may need to adjust the import paths and model definitions based on your project's specific requirements and structure.

45
main.py
View File

@ -1,7 +1,44 @@
Here's a `main.py` file for a FastAPI backend named 'blog_app' with necessary imports and middleware, including SQLite and SQLAlchemy support:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
app = FastAPI(title="Generated Backend")
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Welcome to the generated backend"}
origins = [
"http://localhost",
"http://localhost:8000",
"http://localhost:3000",
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
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()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
This `main.py` file sets up the FastAPI application, configures CORS middleware, and establishes a connection to a SQLite database using SQLAlchemy. Here's a breakdown of the code:
4. Define a dependency function `get_db()` to provide a database session for each request.
Note: You'll need to install the required dependencies (`fastapi`, `uvicorn`, and `sqlalchemy`) before running this code. Additionally, you'll need to create your API routes, models, and other necessary components in separate files and import them as indicated in the placeholder comment.

View File

@ -1,4 +1,9 @@
fastapi
uvicorn
sqlalchemy
pydantic
Here's the `requirements.txt` file for the FastAPI backend named 'blog_app' with the specified dependencies:
This file can be used to install the required dependencies for the 'blog_app' project. To install the dependencies, you can run the following command:
This will install the following packages:
- **sqlalchemy**: A Python SQL toolkit and Object-Relational Mapping (ORM) library for working with databases.