Compare commits

...

2 Commits

18 changed files with 187 additions and 354 deletions

View File

@ -1,25 +1,8 @@
Here's the `dependencies.py` file for the `app/api/core/dependencies/` directory in the `blog_app_igblf` FastAPI backend project: from sqlalchemy.orm import Session
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,63 +1,12 @@
Here's an example of an `activity_tracker.py` file that defines middleware for a FastAPI backend named 'blog_app' using SQLite and SQLAlchemy: import time
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from datetime import datetime from starlette.responses import Response
from typing import Callable, Awaitable from loguru import logger
from sqlalchemy.orm import Session class ActivityTrackerMiddleware(BaseHTTPMiddleware):
from fastapi import Request, Response async def dispatch(self, request: Request, call_next):
from app.db.session import get_db start_time = time.time()
from app.db.models import ActivityLog response = await call_next(request)
process_time = time.time() - start_time
async def log_activity(request: Request, call_next: Callable[[Request], Awaitable[Response]]) -> Response: logger.info(f'{request.method} {request.url} - Process Time: {process_time:.6f} seconds')
start_time = datetime.now() return response
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.

View File

@ -1,26 +1,7 @@
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'
SQLALCHEMY_DATABASE_URL = "sqlite:///blog_app.db" engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={'check_same_thread': False})
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,4 +1,5 @@
Here's the `comments.py` file for the `app/api/v1/models/` directory in the `blog_app_igblf` FastAPI backend: Here's a `comments.py` file with a SQLAlchemy model for comments, following the FastAPI project structure with SQLite and SQLAlchemy:
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
@ -9,24 +10,15 @@ class Comment(Base):
__tablename__ = "comments" __tablename__ = "comments"
id = Column(Integer, primary_key=True, index=True) id = Column(Integer, primary_key=True, index=True)
text = Column(Text, nullable=False) content = Column(Text, nullable=False)
user_id = Column(Integer, ForeignKey("users.id"), nullable=False) author = Column(String, 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}, text='{self.text[:20]}...', user_id={self.user_id}, post_id={self.post_id})" return f"Comment(id={self.id}, content='{self.content[:20]}...', author='{self.author}', post_id={self.post_id})"
Explanation: Explanation:
1. We import the necessary modules from SQLAlchemy: `Column`, `ForeignKey`, `Integer`, `String`, `Text`, and `relationship`. 5. The `content` column stores the text content of the comment and is required (`nullable=False`).
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,10 +1,7 @@
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: 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:
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
@ -12,26 +9,20 @@ 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, nullable=False) title = Column(String, index=True)
content = Column(Text, nullable=False) content = Column(Text)
created_at = Column(TIMESTAMP, server_default=func.now()) user_id = Column(Integer, ForeignKey("users.id"))
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") author = relationship("User", back_populates="posts")
def __repr__(self): 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:
return f"Post(id={self.id}, title='{self.title}', content='{self.content[:20]}...')"
Explanation:
3. The following columns are defined for the `Post` model: 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.
- `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. Note that this code assumes the following:
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,22 +1,29 @@
Here's the `tags.py` file that defines a SQLAlchemy model for tags, located in the `app/api/v1/models/` directory: Here's the `tags.py` file with a SQLAlchemy model for tags, placed 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 import Base from app.db.base_class 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, unique=True, index=True) name = Column(String, nullable=False, unique=True, index=True)
description = Column(String, nullable=True)
def __repr__(self): def __repr__(self):
return f"Tag(id={self.id}, name='{self.name}')" return f"Tag(id={self.id}, name='{self.name}', description='{self.description}')"
Explanation:
The `Tag` model has the following attributes: 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).
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,4 +1,5 @@
Here's the `user.py` file for the `app/api/v1/models/` directory in the `blog_app_igblf` FastAPI backend: 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:
from sqlalchemy import Column, Integer, String, Boolean from sqlalchemy import Column, Integer, String, Boolean
from app.db import Base from app.db import Base
@ -14,12 +15,17 @@ 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}')" return f"User(id={self.id}, username='{self.username}', email='{self.email}', is_active={self.is_active}, is_superuser={self.is_superuser})"
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: Explanation:
- `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,22 +1,2 @@
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,14 +1,17 @@
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
from app.db import get_db router = APIRouter(
from app.models.comment import Comment prefix="/comments",
from app.schemas.comment import CommentCreate, CommentResponse tags=["Comments"],
router = APIRouter() @router.post("/", response_model=CommentResponse)
@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)
@ -16,19 +19,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("/comments", response_model=List[CommentResponse]) @router.get("/", response_model=List[CommentResponse])
def get_all_comments(db: Session = Depends(get_db)): def get_comments(db: Session = Depends(get_db)):
comments = db.query(Comment).all() comments = db.query(Comment).all()
return comments return comments
@router.get("/comments/{comment_id}", response_model=CommentResponse) @router.get("/{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("/comments/{comment_id}", response_model=CommentResponse) @router.put("/{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:
@ -40,22 +43,13 @@ 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("/comments/{comment_id}", status_code=204) @router.delete("/{comment_id}", response_model=CommentResponse)
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 None return comment
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: This file defines the following endpoints:
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,14 +1,18 @@
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("/posts", response_model=PostResponse, status_code=status.HTTP_201_CREATED) @router.post("/", 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)
@ -16,31 +20,30 @@ 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("/posts", response_model=List[PostResponse]) @router.get("/", 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("/posts/{post_id}", response_model=PostResponse) @router.get("/{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("/posts/{post_id}", response_model=PostResponse) @router.put("/{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")
update_data = post.dict(exclude_unset=True) for key, value in post.dict().items():
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("/posts/{post_id}", status_code=status.HTTP_204_NO_CONTENT) @router.delete("/{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:
@ -52,7 +55,5 @@ 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.tag import Tag from app.models import Tag
from app.schemas.tag import TagCreate, TagUpdate, TagOut from app.schemas.tag import TagCreate, TagUpdate, TagOut
router = APIRouter() router = APIRouter()
@ -50,8 +50,11 @@ def delete_tag(tag_id: int, db: Session = Depends(get_db)):
db.commit() db.commit()
return None return None
This file defines the following endpoints: 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:
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,55 +1,61 @@
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.db import get_db from app.core.security import get_current_user
from app.models import User as UserModel from app.db.session import get_db
from app.schemas import User, UserCreate, UserUpdate from app.models import User
from app.schemas.user import UserCreate, UserRead, UserUpdate
router = APIRouter() router = APIRouter(
prefix="/users",
tags=["users"],
@router.get("/users/", response_model=List[User]) @router.post("/", response_model=UserRead)
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)): def create_user(user: UserCreate, db: Session = Depends(get_db)):
db_user = UserModel(**user.dict()) db_user = User(**user.dict())
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.put("/users/{user_id}", response_model=User) @router.get("/", response_model=List[UserRead])
def update_user(user_id: int, user: UserUpdate, db: Session = Depends(get_db)): def read_users(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
db_user = db.query(UserModel).get(user_id) users = db.query(User).all()
return users
@router.get("/{user_id}", response_model=UserRead)
def read_user(user_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
db_user = db.query(User).filter(User.id == user_id).first()
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")
update_data = user.dict(exclude_unset=True) return db_user
for key, value in update_data.items():
@router.put("/{user_id}", response_model=UserRead)
def update_user(user_id: int, user: UserUpdate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
db_user = db.query(User).filter(User.id == user_id).first()
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) setattr(db_user, key, value)
db.add(db_user)
db.commit() db.commit()
db.refresh(db_user) db.refresh(db_user)
return db_user return db_user
@router.delete("/users/{user_id}") @router.delete("/{user_id}", response_model=UserRead)
def delete_user(user_id: int, db: Session = Depends(get_db)): def delete_user(user_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
db_user = db.query(UserModel).get(user_id) db_user = db.query(User).filter(User.id == user_id).first()
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 {"message": "User deleted successfully"} return db_user
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,13 +1,14 @@
Here's the `comments.py` file with Pydantic schemas for comments, following the FastAPI project structure with SQLite and SQLAlchemy: Sure, here's the `comments.py` file for the `app/api/v1/schemas/` directory in the `blog_app_igblf` FastAPI backend:
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=500) content: str = Field(..., min_length=1, max_length=1000)
class CommentCreate(CommentBase): class CommentCreate(CommentBase):
pass pass
@ -17,9 +18,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
@ -30,11 +31,13 @@ class Comment(CommentInDBBase):
class CommentInDB(CommentInDBBase): class CommentInDB(CommentInDBBase):
pass pass
Explanation: This file defines the following Pydantic models for comments:
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,42 +1,31 @@
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 PostBase(BaseModel): class PostCreate(BaseModel):
title: str title: str
content: str content: str
class PostCreate(PostBase): class PostRead(BaseModel):
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 Post(PostInDBBase): class PostUpdate(BaseModel):
pass title: Optional[str] = None
content: Optional[str] = None
class PostList(BaseModel):
__root__: list[Post]
Explanation: Explanation:
1. We import the necessary modules: `typing` for type hints, `pydantic` for defining data models, and `datetime` for handling date and time. 1. `PostCreate` is a Pydantic model that defines the required fields (`title` and `content`) for creating a new post.
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,5 +1,3 @@
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
@ -9,22 +7,21 @@ class TagBase(BaseModel):
class TagCreate(TagBase): class TagCreate(TagBase):
pass pass
class TagUpdate(TagBase): class TagUpdate(BaseModel):
pass name: Optional[str] = None
class TagInDBBase(TagBase): class TagResponse(TagBase):
id: int id: int
name: str
class Config: class Config:
orm_mode = True orm_mode = True
class Tag(TagInDBBase): This file defines the following Pydantic schemas for tags:
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,42 +1,31 @@
Here's the `user.py` file with Pydantic schemas for the user model in the `app/api/v1/schemas/` directory: 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:
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: Optional[EmailStr] = None email: EmailStr
is_active: Optional[bool] = True is_active: Optional[bool] = True
is_superuser: bool = False is_superuser: Optional[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 UserInDBBase(UserBase): class User(UserBase):
id: Optional[int] = None id: int
class Config: class Config:
orm_mode = True orm_mode = True
class User(UserInDBBase): This file defines the following Pydantic schemas:
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,44 +1,10 @@
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 fastapi.middleware.cors import CORSMiddleware from app.api.db.database import engine, Base
from sqlalchemy import create_engine from app.api.v1.routes import router
from sqlalchemy.ext.declarative import declarative_base from app.api.core.middleware.activity_tracker import ActivityTrackerMiddleware
from sqlalchemy.orm import sessionmaker
app = FastAPI() app = FastAPI()
app.add_middleware(ActivityTrackerMiddleware)
origins = [ app.include_router(router, prefix='/v1')
"http://localhost", @app.on_event('startup')
"http://localhost:8000", def startup():
"http://localhost:3000", Base.metadata.create_all(bind=engine)
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,9 +1,5 @@
Here's the `requirements.txt` file for the FastAPI backend named 'blog_app' with the specified dependencies: fastapi
uvicorn
sqlalchemy
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: pydantic
loguru
This will install the following packages:
- **sqlalchemy**: A Python SQL toolkit and Object-Relational Mapping (ORM) library for working with databases.