Compare commits

..

No commits in common. "update-1742546020" and "main" have entirely different histories.

18 changed files with 358 additions and 191 deletions

View File

@ -1,8 +1,25 @@
from sqlalchemy.orm import Session Here's the `dependencies.py` file for the `app/api/core/dependencies/` directory in the `blog_app_igblf` FastAPI backend project:
from app.api.db.database import SessionLocal
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(): def get_db():
db = SessionLocal() db = SessionLocal()
try: try:
yield db yield db
finally: finally:
db.close() db.close()
This `dependencies.py` file contains the following components:

View File

@ -1,12 +1,63 @@
import time 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 starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response from datetime import datetime
from loguru import logger from typing import Callable, Awaitable
class ActivityTrackerMiddleware(BaseHTTPMiddleware): from sqlalchemy.orm import Session
async def dispatch(self, request: Request, call_next): from fastapi import Request, Response
start_time = time.time() 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) response = await call_next(request)
process_time = time.time() - start_time process_time = (datetime.now() - start_time).total_seconds() * 1000
logger.info(f'{request.method} {request.url} - Process Time: {process_time:.6f} seconds')
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 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.

View File

@ -1,7 +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 import create_engine
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import sessionmaker
SQLALCHEMY_DATABASE_URL = 'sqlite:///./blog_app.db'
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={'check_same_thread': False}) 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) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base() 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

@ -1,5 +1,4 @@
Here's a `comments.py` file with a SQLAlchemy model for comments, following the FastAPI project structure with SQLite and SQLAlchemy: 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 import Column, ForeignKey, Integer, String, Text
from sqlalchemy.orm import relationship from sqlalchemy.orm import relationship
@ -10,15 +9,24 @@ class Comment(Base):
__tablename__ = "comments" __tablename__ = "comments"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
content = Column(Text, nullable=False) text = Column(Text, nullable=False)
author = Column(String, nullable=False) user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
post_id = Column(Integer, ForeignKey("posts.id"), nullable=False) post_id = Column(Integer, ForeignKey("posts.id"), nullable=False)
user = relationship("User", back_populates="comments")
post = relationship("Post", back_populates="comments") post = relationship("Post", back_populates="comments")
def __repr__(self): def __repr__(self):
return f"Comment(id={self.id}, content='{self.content[:20]}...', author='{self.author}', post_id={self.post_id})" return f"Comment(id={self.id}, text='{self.text[:20]}...', user_id={self.user_id}, post_id={self.post_id})"
Explanation: Explanation:
5. The `content` column stores the text content of the comment and is required (`nullable=False`). 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

@ -1,7 +1,10 @@
Here's the `posts.py` file for the `app/api/v1/models/` directory of the `blog_app_igblf` FastAPI backend, defining a SQLAlchemy model for posts: 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, ForeignKey, Integer, String, Text
from sqlalchemy import Column, Integer, String, Text, ForeignKey
from sqlalchemy.orm import relationship from sqlalchemy.orm import relationship
from sqlalchemy.sql.sqltypes import TIMESTAMP
from sqlalchemy.sql import func
from app.db import Base from app.db import Base
@ -9,20 +12,26 @@ class Post(Base):
__tablename__ = "posts" __tablename__ = "posts"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
title = Column(String, index=True) title = Column(String, nullable=False)
content = Column(Text) content = Column(Text, nullable=False)
user_id = Column(Integer, ForeignKey("users.id")) 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)
author = relationship("User", back_populates="posts") user = relationship("User", back_populates="posts")
This file defines a `Post` model that inherits from the `Base` class (assumed to be defined in `app.db`). The `Post` model has the following columns: def __repr__(self):
return f"Post(id={self.id}, title='{self.title}', content='{self.content[:20]}...')"
Explanation:
The `author` attribute is a relationship with the `User` model (assumed to be defined elsewhere), using the `back_populates` parameter to create a bidirectional relationship. This means that each `Post` instance will have an `author` attribute that references the associated `User` instance, and each `User` instance will have a `posts` attribute that contains a list of associated `Post` instances. 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 that this code assumes the following: 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.
2. The `User` model is defined elsewhere (e.g., `app/api/v1/models/users.py`).
3. The necessary imports for SQLAlchemy are available (e.g., `from sqlalchemy import ...`).
Make sure to import this model in the appropriate places (e.g., `app/main.py`) and create the necessary database tables using SQLAlchemy's database migration tools or by running the appropriate commands.

View File

@ -1,29 +1,22 @@
Here's the `tags.py` file with a SQLAlchemy model for tags, placed in the `app/api/v1/models/` directory: Here's the `tags.py` file that defines a SQLAlchemy model for tags, located in the `app/api/v1/models/` directory:
from typing import Optional
from sqlalchemy import Column, Integer, String from sqlalchemy import Column, Integer, String
from app.db.base_class import Base from app.db import Base
class Tag(Base): class Tag(Base):
__tablename__ = "tags" __tablename__ = "tags"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False, unique=True, index=True) name = Column(String, unique=True, index=True)
description = Column(String, nullable=True)
def __repr__(self): def __repr__(self):
return f"Tag(id={self.id}, name='{self.name}', description='{self.description}')" return f"Tag(id={self.id}, name='{self.name}')"
Explanation:
1. We import the necessary modules: `typing` for type hints, `sqlalchemy` for defining the database model, and `app.db.base_class` for the base class that inherits from `Base` (assuming you have a `base_class.py` file in the `app/db/` directory). 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.
Note: This code assumes that you have already set up the necessary database connection and configured SQLAlchemy in your FastAPI application. If not, you'll need to add the required configuration and import statements accordingly.

View File

@ -1,5 +1,4 @@
Sure, here's the `user.py` file for the `app/api/v1/models/` directory of the `blog_app` FastAPI backend project using SQLAlchemy with SQLite: 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 sqlalchemy import Column, Integer, String, Boolean
from app.db import Base from app.db import Base
@ -15,17 +14,12 @@ class User(Base):
is_superuser = Column(Boolean, default=False) is_superuser = Column(Boolean, default=False)
def __repr__(self): def __repr__(self):
return f"User(id={self.id}, username='{self.username}', email='{self.email}', is_active={self.is_active}, is_superuser={self.is_superuser})" return f"User(id={self.id}, username='{self.username}', email='{self.email}')"
Explanation: 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.
4. We define the following columns for the `User` model:
- `id`: an integer primary key with an index
- `username`: a string column that is unique and indexed
- `email`: a string column that is unique and indexed
- `hashed_password`: a string column to store the hashed password
- `is_active`: a boolean column to indicate if the user is active or not (default is `True`)
- `is_superuser`: a boolean column to indicate if the user is a superuser or not (default is `False`)

View File

@ -1,2 +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 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 = 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

@ -1,17 +1,14 @@
Here's the `comments.py` file with CRUD endpoints for comments:
from typing import List 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.db.database import get_db
from app.models import Comment
from app.schemas import CommentCreate, CommentResponse
router = APIRouter( from app.db import get_db
prefix="/comments", from app.models.comment import Comment
tags=["Comments"], from app.schemas.comment import CommentCreate, CommentResponse
@router.post("/", response_model=CommentResponse) router = APIRouter()
@router.post("/comments", response_model=CommentResponse, status_code=201)
def create_comment(comment: CommentCreate, db: Session = Depends(get_db)): def create_comment(comment: CommentCreate, db: Session = Depends(get_db)):
db_comment = Comment(**comment.dict()) db_comment = Comment(**comment.dict())
db.add(db_comment) db.add(db_comment)
@ -19,19 +16,19 @@ def create_comment(comment: CommentCreate, db: Session = Depends(get_db)):
db.refresh(db_comment) db.refresh(db_comment)
return db_comment return db_comment
@router.get("/", response_model=List[CommentResponse]) @router.get("/comments", response_model=List[CommentResponse])
def get_comments(db: Session = Depends(get_db)): def get_all_comments(db: Session = Depends(get_db)):
comments = db.query(Comment).all() comments = db.query(Comment).all()
return comments return comments
@router.get("/{comment_id}", response_model=CommentResponse) @router.get("/comments/{comment_id}", response_model=CommentResponse)
def get_comment(comment_id: int, db: Session = Depends(get_db)): def get_comment(comment_id: int, db: Session = Depends(get_db)):
comment = db.query(Comment).filter(Comment.id == comment_id).first() comment = db.query(Comment).filter(Comment.id == comment_id).first()
if not comment: if not comment:
raise HTTPException(status_code=404, detail="Comment not found") raise HTTPException(status_code=404, detail="Comment not found")
return comment return comment
@router.put("/{comment_id}", response_model=CommentResponse) @router.put("/comments/{comment_id}", response_model=CommentResponse)
def update_comment(comment_id: int, comment: CommentCreate, db: Session = Depends(get_db)): def update_comment(comment_id: int, comment: CommentCreate, db: Session = Depends(get_db)):
db_comment = db.query(Comment).filter(Comment.id == comment_id).first() db_comment = db.query(Comment).filter(Comment.id == comment_id).first()
if not db_comment: if not db_comment:
@ -43,13 +40,22 @@ def update_comment(comment_id: int, comment: CommentCreate, db: Session = Depend
db.refresh(db_comment) db.refresh(db_comment)
return db_comment return db_comment
@router.delete("/{comment_id}", response_model=CommentResponse) @router.delete("/comments/{comment_id}", status_code=204)
def delete_comment(comment_id: int, db: Session = Depends(get_db)): def delete_comment(comment_id: int, db: Session = Depends(get_db)):
comment = db.query(Comment).filter(Comment.id == comment_id).first() comment = db.query(Comment).filter(Comment.id == comment_id).first()
if not comment: if not comment:
raise HTTPException(status_code=404, detail="Comment not found") raise HTTPException(status_code=404, detail="Comment not found")
db.delete(comment) db.delete(comment)
db.commit() db.commit()
return comment return None
This file defines the following endpoints: 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

@ -1,18 +1,14 @@
Here's the `posts.py` file with CRUD endpoints for posts:
from typing import List from typing import List
from fastapi import APIRouter, Depends, HTTPException, status from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from app.db import get_db
from app.models import Post from app.models import Post
from app.schemas import PostCreate, PostResponse from app.schemas import PostCreate, PostResponse
from app.database import get_db
router = APIRouter( router = APIRouter()
prefix="/posts",
tags=["Posts"],
@router.post("/", response_model=PostResponse, status_code=status.HTTP_201_CREATED) @router.post("/posts", response_model=PostResponse, status_code=status.HTTP_201_CREATED)
def create_post(post: PostCreate, db: Session = Depends(get_db)): def create_post(post: PostCreate, db: Session = Depends(get_db)):
new_post = Post(**post.dict()) new_post = Post(**post.dict())
db.add(new_post) db.add(new_post)
@ -20,30 +16,31 @@ def create_post(post: PostCreate, db: Session = Depends(get_db)):
db.refresh(new_post) db.refresh(new_post)
return new_post return new_post
@router.get("/", response_model=List[PostResponse]) @router.get("/posts", response_model=List[PostResponse])
def get_all_posts(db: Session = Depends(get_db)): def get_all_posts(db: Session = Depends(get_db)):
posts = db.query(Post).all() posts = db.query(Post).all()
return posts return posts
@router.get("/{post_id}", response_model=PostResponse) @router.get("/posts/{post_id}", response_model=PostResponse)
def get_post(post_id: int, db: Session = Depends(get_db)): def get_post(post_id: int, db: Session = Depends(get_db)):
post = db.query(Post).filter(Post.id == post_id).first() post = db.query(Post).filter(Post.id == post_id).first()
if not post: if not post:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Post not found") raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Post not found")
return post return post
@router.put("/{post_id}", response_model=PostResponse) @router.put("/posts/{post_id}", response_model=PostResponse)
def update_post(post_id: int, post: PostCreate, db: Session = Depends(get_db)): def update_post(post_id: int, post: PostCreate, db: Session = Depends(get_db)):
db_post = db.query(Post).filter(Post.id == post_id).first() db_post = db.query(Post).filter(Post.id == post_id).first()
if not db_post: if not db_post:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Post not found") raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Post not found")
for key, value in post.dict().items(): update_data = post.dict(exclude_unset=True)
for key, value in update_data.items():
setattr(db_post, key, value) setattr(db_post, key, value)
db.commit() db.commit()
db.refresh(db_post) db.refresh(db_post)
return db_post return db_post
@router.delete("/{post_id}", status_code=status.HTTP_204_NO_CONTENT) @router.delete("/posts/{post_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_post(post_id: int, db: Session = Depends(get_db)): def delete_post(post_id: int, db: Session = Depends(get_db)):
post = db.query(Post).filter(Post.id == post_id).first() post = db.query(Post).filter(Post.id == post_id).first()
if not post: if not post:
@ -55,5 +52,7 @@ def delete_post(post_id: int, db: Session = Depends(get_db)):
This file defines the following endpoints: 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: Make sure you have the `Post` model, `PostCreate` and `PostResponse` schemas, and the `get_db` dependency defined in your project.
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.

View File

@ -3,7 +3,7 @@ from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from app.db.session import get_db from app.db.session import get_db
from app.models import Tag from app.models.tag import Tag
from app.schemas.tag import TagCreate, TagUpdate, TagOut from app.schemas.tag import TagCreate, TagUpdate, TagOut
router = APIRouter() router = APIRouter()
@ -50,11 +50,8 @@ def delete_tag(tag_id: int, db: Session = Depends(get_db)):
db.commit() db.commit()
return None return None
This code defines a set of CRUD endpoints for managing tags in the `blog_app_igblf` FastAPI application. Here's a breakdown of the different endpoints: This file defines the following endpoints:
1. `POST /tags`: Creates a new tag. It expects a `TagCreate` Pydantic model in the request body and returns the created `TagOut` model with a status code of 201 (Created).
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`).
5. `DELETE /tags/{tag_id}`: Deletes a tag by its ID. If the tag is found, it is deleted from the database and returns a 204 (No Content) status code. If the tag is not found, it raises an HTTP 404 exception.

View File

@ -1,61 +1,55 @@
Here's the `user.py` file with CRUD endpoints for the `User` model:
from typing import List 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.core.security import get_current_user from app.db import get_db
from app.db.session import get_db from app.models import User as UserModel
from app.models import User from app.schemas import User, UserCreate, UserUpdate
from app.schemas.user import UserCreate, UserRead, UserUpdate
router = APIRouter( router = APIRouter()
prefix="/users",
tags=["users"],
@router.post("/", response_model=UserRead) @router.get("/users/", response_model=List[User])
def create_user(user: UserCreate, db: Session = Depends(get_db)): def read_users(db: Session = Depends(get_db)):
db_user = User(**user.dict()) users = db.query(UserModel).all()
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
@router.get("/", response_model=List[UserRead])
def read_users(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
users = db.query(User).all()
return users return users
@router.get("/{user_id}", response_model=UserRead) @router.get("/users/{user_id}", response_model=User)
def read_user(user_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): def read_user(user_id: int, db: Session = Depends(get_db)):
db_user = db.query(User).filter(User.id == user_id).first() user = db.query(UserModel).get(user_id)
if not db_user: if not user:
raise HTTPException(status_code=404, detail="User not found") raise HTTPException(status_code=404, detail="User not found")
return db_user return user
@router.put("/{user_id}", response_model=UserRead) @router.post("/users/", response_model=User)
def update_user(user_id: int, user: UserUpdate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): def create_user(user: UserCreate, db: Session = Depends(get_db)):
db_user = db.query(User).filter(User.id == user_id).first() db_user = UserModel(**user.dict())
if not db_user:
raise HTTPException(status_code=404, detail="User not found")
user_data = user.dict(exclude_unset=True)
for key, value in user_data.items():
setattr(db_user, key, value)
db.add(db_user) db.add(db_user)
db.commit() db.commit()
db.refresh(db_user) db.refresh(db_user)
return db_user return db_user
@router.delete("/{user_id}", response_model=UserRead) @router.put("/users/{user_id}", response_model=User)
def delete_user(user_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): def update_user(user_id: int, user: UserUpdate, db: Session = Depends(get_db)):
db_user = db.query(User).filter(User.id == user_id).first() 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: if not db_user:
raise HTTPException(status_code=404, detail="User not found") raise HTTPException(status_code=404, detail="User not found")
db.delete(db_user) db.delete(db_user)
db.commit() db.commit()
return db_user return {"message": "User deleted successfully"}
This file defines the following endpoints: This file defines the following endpoints:
The endpoints use SQLAlchemy models and Pydantic schemas for data validation and serialization. The `get_current_user` dependency is used to ensure that only authenticated users can access certain endpoints (e.g., read all users, read a single user, update a user, and delete a user).
Note that you'll need to define the `User`, `UserCreate`, `UserRead`, and `UserUpdate` models and schemas in separate files (e.g., `app/models.py` and `app/schemas/user.py`). Additionally, you'll need to implement the `get_current_user` function in `app/core/security.py` to handle user authentication and authorization.

View File

@ -1,14 +1,13 @@
Sure, here's the `comments.py` file for the `app/api/v1/schemas/` directory in the `blog_app_igblf` FastAPI backend: 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 datetime import datetime
from typing import Optional from typing import Optional
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from app.db.base_class import Base
class CommentBase(BaseModel): class CommentBase(BaseModel):
content: str = Field(..., min_length=1, max_length=1000) content: str = Field(..., min_length=1, max_length=500)
class CommentCreate(CommentBase): class CommentCreate(CommentBase):
pass pass
@ -18,9 +17,9 @@ class CommentUpdate(CommentBase):
class CommentInDBBase(CommentBase): class CommentInDBBase(CommentBase):
id: int id: int
post_id: int
created_at: datetime created_at: datetime
updated_at: Optional[datetime] = None updated_at: Optional[datetime] = None
post_id: int
class Config: class Config:
orm_mode = True orm_mode = True
@ -31,13 +30,11 @@ class Comment(CommentInDBBase):
class CommentInDB(CommentInDBBase): class CommentInDB(CommentInDBBase):
pass pass
This file defines the following Pydantic models for comments: 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.
Note: You may need to adjust the import statements and the `Base` class import based on the actual structure of your `blog_app_igblf` project.

View File

@ -1,31 +1,42 @@
Here's the `posts.py` file with Pydantic schemas for posts, which can be placed in the `app/api/v1/schemas/` directory:
from typing import Optional from typing import Optional
from pydantic import BaseModel from pydantic import BaseModel
from datetime import datetime from datetime import datetime
class PostCreate(BaseModel): class PostBase(BaseModel):
title: str title: str
content: str content: str
class PostRead(BaseModel): class PostCreate(PostBase):
pass
class PostUpdate(PostBase):
pass
class PostInDBBase(PostBase):
id: int id: int
title: str
content: str
created_at: datetime created_at: datetime
updated_at: Optional[datetime] = None updated_at: Optional[datetime] = None
class Config: class Config:
orm_mode = True orm_mode = True
class PostUpdate(BaseModel): class Post(PostInDBBase):
title: Optional[str] = None pass
content: Optional[str] = None
class PostList(BaseModel):
__root__: list[Post]
Explanation: Explanation:
1. `PostCreate` is a Pydantic model that defines the required fields (`title` and `content`) for creating a new post. 1. We import the necessary modules: `typing` for type hints, `pydantic` for defining data models, and `datetime` for handling date and time.
3. `PostUpdate` is a Pydantic model that defines the optional fields (`title` and `content`) for updating an existing post.
2. `PostBase` is a base Pydantic model that defines the common fields for a post: `title` and `content`.
Note: Make sure to import the necessary dependencies (`typing`, `pydantic`, and `datetime`) at the top of the file.
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

@ -1,3 +1,5 @@
Here's the `tags.py` file with Pydantic schemas for tags, located in the `app/api/v1/schemas/` directory:
from typing import Optional from typing import Optional
from pydantic import BaseModel from pydantic import BaseModel
@ -7,21 +9,22 @@ class TagBase(BaseModel):
class TagCreate(TagBase): class TagCreate(TagBase):
pass pass
class TagUpdate(BaseModel): class TagUpdate(TagBase):
name: Optional[str] = None pass
class TagResponse(TagBase): class TagInDBBase(TagBase):
id: int id: int
name: str
class Config: class Config:
orm_mode = True orm_mode = True
This file defines the following Pydantic schemas for tags: 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.
The `orm_mode = True` configuration in the `TagResponse` schema tells Pydantic to read data from an ORM model (SQLAlchemy in this case) or a dict-like object, rather than just a dict.
Note: This file assumes that you have the necessary imports and dependencies set up in your FastAPI project structure, including Pydantic and SQLAlchemy (if you're using it for database operations).

View File

@ -1,31 +1,42 @@
Here's the `user.py` file that defines Pydantic schemas for the user model in the `app/api/v1/schemas/` directory of the `blog_app_igblf` FastAPI backend: 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 typing import Optional
from pydantic import BaseModel, EmailStr from pydantic import BaseModel, EmailStr
class UserBase(BaseModel): class UserBase(BaseModel):
email: EmailStr email: Optional[EmailStr] = None
is_active: Optional[bool] = True is_active: Optional[bool] = True
is_superuser: Optional[bool] = False is_superuser: bool = False
full_name: Optional[str] = None full_name: Optional[str] = None
class UserCreate(UserBase): class UserCreate(UserBase):
email: EmailStr
password: str password: str
class UserUpdate(UserBase): class UserUpdate(UserBase):
password: Optional[str] = None password: Optional[str] = None
class User(UserBase): class UserInDBBase(UserBase):
id: int id: Optional[int] = None
class Config: class Config:
orm_mode = True orm_mode = True
This file defines the following Pydantic schemas: 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: Make sure to import the necessary dependencies, such as `pydantic` and `typing`, at the top of the file.
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.

50
main.py
View File

@ -1,10 +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 import FastAPI
from app.api.db.database import engine, Base from fastapi.middleware.cors import CORSMiddleware
from app.api.v1.routes import router from sqlalchemy import create_engine
from app.api.core.middleware.activity_tracker import ActivityTrackerMiddleware from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
app = FastAPI() app = FastAPI()
app.add_middleware(ActivityTrackerMiddleware)
app.include_router(router, prefix='/v1') origins = [
@app.on_event('startup') "http://localhost",
def startup(): "http://localhost:8000",
Base.metadata.create_all(bind=engine) "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,5 +1,9 @@
fastapi Here's the `requirements.txt` file for the FastAPI backend named 'blog_app' with the specified dependencies:
uvicorn
sqlalchemy
pydantic 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:
loguru
This will install the following packages:
- **sqlalchemy**: A Python SQL toolkit and Object-Relational Mapping (ORM) library for working with databases.