Compare commits

...

3 Commits

25 changed files with 181 additions and 328 deletions

1
.gitignore vendored
View File

@ -1 +0,0 @@
__pycache__\n*.pyc\n*.db\nvenv/\n

View File

View File

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 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()
from sqlalchemy.orm import Session
from app.api.db.database import SessionLocal
def get_db():
db = SessionLocal()
try:
yield db
finally:
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:
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.
import time
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response
from loguru import logger
class ActivityTrackerMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
logger.info(f'{request.method} {request.url} - Process Time: {process_time:.6f} seconds')
return response

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.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}
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

View File

@ -1,32 +1,40 @@
Here's the `comments.py` file for the `app/api/v1/models/` directory in the `blog_app_igblf` FastAPI backend:
Here's the `comments.py` file for the `app/api/v1/models/` directory in the `blog_app_igblf` FastAPI backend project, defining a SQLAlchemy model for comments:
from typing import Optional
from sqlalchemy import Column, ForeignKey, Integer, String, Text
from sqlalchemy.orm import relationship
from app.db.base_class import Base
from app.db 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)
author_id = Column(Integer, ForeignKey("users.id"), nullable=False)
content = Column(Text, nullable=False)
created_at = Column(String, nullable=False)
updated_at = Column(String, nullable=True)
user = relationship("User", back_populates="comments")
post = relationship("Post", back_populates="comments")
author = relationship("User", 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})"
return f"Comment(id={self.id}, post_id={self.post_id}, author_id={self.author_id}, content='{self.content}', created_at='{self.created_at}', updated_at='{self.updated_at}')"
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.
- `id`: An auto-incrementing primary key column of type `Integer`.
- `post_id`: A foreign key column of type `Integer` that references the `id` column of the `posts` table.
- `author_id`: A foreign key column of type `Integer` that references the `id` column of the `users` table.
- `content`: A `Text` column that stores the comment content.
- `created_at`: A `String` column that stores the creation timestamp of the comment.
- `updated_at`: An optional `String` column that stores the last update timestamp of the comment.
- `post`: A relationship with the `Post` model, where each comment belongs to a post.
- `author`: A relationship with the `User` model, where each comment is written by a user.
Note: This implementation assumes that you have already defined the `Post` and `User` models in separate files, and that they have the necessary relationships defined to work with the `Comment` model.

View File

@ -1,7 +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 with the SQLAlchemy model for posts:
from sqlalchemy import Column, Integer, String, Text, ForeignKey
from sqlalchemy import Column, ForeignKey, Integer, String, Text
from sqlalchemy.orm import relationship
from sqlalchemy.sql.sqltypes import TIMESTAMP
from sqlalchemy.sql import func
@ -25,13 +25,10 @@ class Post(Base):
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.
5. We define the columns for the `Post` model:
- `id`: Integer primary key and index column.
- `title`: String column that cannot be null.
- `content`: Text column that cannot be null.
- `created_at`: TIMESTAMP column with a default value of the current server time.
- `updated_at`: TIMESTAMP column with a default value of the current server time and updated on each update.
- `user_id`: Integer column that is a foreign key referencing the `id` column of the `users` table.

View File

@ -1,22 +1,26 @@
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 for the `app/api/v1/models/` directory of the `blog_app` FastAPI backend, defining a SQLAlchemy model for tags:
from sqlalchemy import Column, Integer, String
from app.db import Base
from app.db.base_class import Base
class Tag(Base):
__tablename__ = "tags"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, unique=True, index=True)
name = Column(String, nullable=False, unique=True, index=True)
def __repr__(self):
return f"Tag(id={self.id}, name='{self.name}')"
Explanation:
The `Tag` model has the following attributes:
2. `from app.db.base_class import Base`: We import the `Base` class from the `base_class.py` file, which is typically a base class that inherits from SQLAlchemy's `declarative_base()`.
3. `class Tag(Base):`: We define a `Tag` class that inherits from the `Base` class.
4. `__tablename__ = "tags"`: We set the `__tablename__` attribute to specify the name of the database table for this model.
5. `id = Column(Integer, primary_key=True, index=True)`: We define an `id` column of type `Integer`, which is the primary key and indexed for faster lookups.
6. `name = Column(String, nullable=False, unique=True, index=True)`: We define a `name` column of type `String`, which cannot be null, must be unique, and is indexed for faster lookups.
7. `def __repr__(self):`: We define a `__repr__` method to provide a string representation of the `Tag` object, which is useful for debugging and logging purposes.
This model defines a simple `Tag` table with two columns: `id` (primary key) and `name` (unique string). The `__repr__` method allows you to print a readable representation of a `Tag` instance.
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.
Make sure to import this model in your application and create the necessary database tables using SQLAlchemy's `create_all()` method or an Alembic migration script.

View File

@ -1,7 +1,7 @@
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, DateTime
from sqlalchemy.orm import relationship
from app.db import Base
import datetime
class User(Base):
__tablename__ = "users"
@ -9,17 +9,25 @@ class User(Base):
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)
password = Column(String)
created_at = Column(DateTime, default=datetime.datetime.utcnow)
updated_at = Column(DateTime, default=datetime.datetime.utcnow)
posts = relationship("Post", back_populates="author")
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:
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`).
3. We define the table name using `__tablename__ = "users"`.
4. We define the columns for the `User` model:
- `id`: Integer primary key and index
- `username`: String, unique, and indexed
- `email`: String, unique, and indexed
- `password`: String
- `created_at`: DateTime, default set to the current UTC time
- `updated_at`: DateTime, default set to the current UTC time
5. We define a relationship `posts` that relates the `User` model to the `Post` model (which you'll need to define separately). This relationship is set up using `back_populates` to allow bidirectional access between `User` and `Post` instances.
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.
Note: This code assumes that you have already defined a `Base` class in `app/db.py` and that you will define a `Post` model separately. Make sure to import the necessary modules and create the database tables using SQLAlchemy's `create_all` method.

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 .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

@ -1,14 +1,19 @@
Here's an example of the `comments.py` file with CRUD endpoints for comments using FastAPI and SQLAlchemy:
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
from app.models import Comment
from app.schemas import CommentCreate, CommentResponse
router = APIRouter()
router = APIRouter(
prefix="/comments",
tags=["Comments"],
@router.post("/comments", response_model=CommentResponse, status_code=201)
@router.post("/", 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)
@ -16,46 +21,40 @@ def create_comment(comment: CommentCreate, db: Session = Depends(get_db)):
db.refresh(db_comment)
return db_comment
@router.get("/comments", response_model=List[CommentResponse])
def get_all_comments(db: Session = Depends(get_db)):
@router.get("/", response_model=List[CommentResponse])
def get_comments(db: Session = Depends(get_db)):
comments = db.query(Comment).all()
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)):
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)
@router.put("/{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)
for field, value in comment.dict().items():
setattr(db_comment, field, value)
db.commit()
db.refresh(db_comment)
return db_comment
@router.delete("/comments/{comment_id}", status_code=204)
@router.delete("/{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
return {"message": "Comment deleted successfully"}
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.
This file defines the following endpoints:

View File

@ -1,5 +1,7 @@
Here's the `posts.py` file with CRUD endpoints for posts:
from typing import List
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.db import get_db
@ -8,51 +10,48 @@ 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)):
def get_posts(db: Session = Depends(get_db)):
posts = db.query(Post).all()
return posts
@router.post("/posts", response_model=PostResponse)
def create_post(post: PostCreate, db: Session = Depends(get_db)):
db_post = Post(**post.dict())
db.add(db_post)
db.commit()
db.refresh(db_post)
return db_post
@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")
raise HTTPException(status_code=404, 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)
raise HTTPException(status_code=404, detail="Post not found")
for field, value in post.dict().items():
setattr(db_post, field, value)
db.commit()
db.refresh(db_post)
return db_post
@router.delete("/posts/{post_id}", status_code=status.HTTP_204_NO_CONTENT)
@router.delete("/posts/{post_id}", response_model=PostResponse)
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")
raise HTTPException(status_code=404, detail="Post not found")
db.delete(post)
db.commit()
return
return post
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.
Note: Make sure to import the necessary models and schemas in the `app/models.py` and `app/schemas.py` files, respectively.

View File

@ -4,11 +4,11 @@ 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
from app.schemas.tag import TagCreate, TagUpdate, TagResponse
router = APIRouter()
@router.post("/tags", response_model=TagOut, status_code=201)
@router.post("/tags", response_model=TagResponse, status_code=201)
def create_tag(tag: TagCreate, db: Session = Depends(get_db)):
db_tag = Tag(**tag.dict())
db.add(db_tag)
@ -16,19 +16,19 @@ def create_tag(tag: TagCreate, db: Session = Depends(get_db)):
db.refresh(db_tag)
return db_tag
@router.get("/tags", response_model=List[TagOut])
def read_tags(db: Session = Depends(get_db)):
@router.get("/tags", response_model=List[TagResponse])
def get_all_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)):
@router.get("/tags/{tag_id}", response_model=TagResponse)
def get_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)
@router.put("/tags/{tag_id}", response_model=TagResponse)
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:
@ -36,7 +36,6 @@ def update_tag(tag_id: int, tag: TagUpdate, db: Session = Depends(get_db)):
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
@ -54,4 +53,4 @@ 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`).
Note: This code assumes that you have already defined the `Tag` model and the `TagCreate`, `TagUpdate`, and `TagResponse` Pydantic schemas in their respective files. Additionally, you need to include this `tags.py` file in your FastAPI application by adding it to the router.

View File

@ -1,29 +1,15 @@
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
from app.models.user import User as UserModel
from app.schemas.user import User, UserCreate, UserUpdate
router = APIRouter()
router = APIRouter(
prefix="/users",
tags=["Users"],
@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)
@router.post("/", response_model=User)
def create_user(user: UserCreate, db: Session = Depends(get_db)):
db_user = UserModel(**user.dict())
db.add(db_user)
@ -31,9 +17,21 @@ def create_user(user: UserCreate, db: Session = Depends(get_db)):
db.refresh(db_user)
return db_user
@router.put("/users/{user_id}", response_model=User)
@router.get("/", response_model=List[User])
def read_users(db: Session = Depends(get_db)):
users = db.query(UserModel).all()
return users
@router.get("/{user_id}", response_model=User)
def read_user(user_id: int, db: Session = Depends(get_db)):
db_user = db.query(UserModel).filter(UserModel.id == user_id).first()
if not db_user:
raise HTTPException(status_code=404, detail="User not found")
return db_user
@router.put("/{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)
db_user = db.query(UserModel).filter(UserModel.id == user_id).first()
if not db_user:
raise HTTPException(status_code=404, detail="User not found")
update_data = user.dict(exclude_unset=True)
@ -43,9 +41,9 @@ def update_user(user_id: int, user: UserUpdate, db: Session = Depends(get_db)):
db.refresh(db_user)
return db_user
@router.delete("/users/{user_id}")
@router.delete("/{user_id}")
def delete_user(user_id: int, db: Session = Depends(get_db)):
db_user = db.query(UserModel).get(user_id)
db_user = db.query(UserModel).filter(UserModel.id == user_id).first()
if not db_user:
raise HTTPException(status_code=404, detail="User not found")
db.delete(db_user)

View File

@ -1,13 +1,12 @@
Here's the `comments.py` file with Pydantic schemas for comments, following the FastAPI project structure with SQLite and SQLAlchemy:
Here's the `comments.py` file for the `app/api/v1/schemas/` directory in the `blog_app_igblf` FastAPI backend project:
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field
from pydantic import BaseModel
class CommentBase(BaseModel):
content: str = Field(..., min_length=1, max_length=500)
content: str
class CommentCreate(CommentBase):
pass
@ -30,11 +29,6 @@ class Comment(CommentInDBBase):
class CommentInDB(CommentInDBBase):
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.
4. `CommentInDBBase`: A base model that includes fields for the comment ID (`id`), the associated post ID (`post_id`), the creation timestamp (`created_at`), and an optional update timestamp (`updated_at`). This model inherits from `CommentBase` and includes the `orm_mode` configuration to allow reading data from an SQLAlchemy model.

View File

@ -1,6 +1,9 @@
Here's the `posts.py` file with Pydantic schemas for posts, following the FastAPI project structure with SQLite and SQLAlchemy:
from typing import Optional
from pydantic import BaseModel
from datetime import datetime
from pydantic import BaseModel
class PostBase(BaseModel):
title: str
@ -23,20 +26,14 @@ class PostInDBBase(PostBase):
class Post(PostInDBBase):
pass
class PostList(BaseModel):
__root__: list[Post]
class PostInDB(PostInDBBase):
pass
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.
1. We import the necessary modules: `typing` for type hints, `datetime` for dealing with date and time objects, and `pydantic` for defining data models.
Make sure to install the required dependencies (`pydantic` and `sqlalchemy`) in your project environment if you haven't already done so.
5. `PostInDBBase` inherits from `PostBase` and includes additional fields: `id`, `created_at`, and `updated_at`. It also sets the `orm_mode` configuration to `True` for compatibility with SQLAlchemy models.

View File

@ -1,4 +1,4 @@
Here's the `tags.py` file with Pydantic schemas for tags, located in the `app/api/v1/schemas/` directory:
Here's the `tags.py` file with Pydantic schemas for tags, which can be placed in the `app/api/v1/schemas/` directory:
from typing import Optional
from pydantic import BaseModel
@ -27,4 +27,5 @@ class TagInDB(TagInDBBase):
Explanation:
1. We import the necessary modules: `typing` for type hints and `pydantic` for defining data models.
1. We import the necessary dependencies: `typing` for type hints and `pydantic` for defining data models.
5. `TagInDBBase` inherits from `TagBase` and includes an `id` field. It also sets `orm_mode = True` in the `Config` class, which allows Pydantic to work with SQLAlchemy models.

View File

@ -1,16 +1,15 @@
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 with Pydantic schemas for user in the `app/api/v1/schemas/` directory:
from typing import Optional
from pydantic import BaseModel, EmailStr
class UserBase(BaseModel):
email: Optional[EmailStr] = None
email: EmailStr
is_active: Optional[bool] = True
is_superuser: bool = False
full_name: Optional[str] = None
class UserCreate(UserBase):
email: EmailStr
password: str
class UserUpdate(UserBase):
@ -30,7 +29,7 @@ class UserInDB(UserInDBBase):
Explanation:
1. We import the necessary modules: `typing` for type hints, and `pydantic` for defining data models.
1. We import the necessary modules: `typing` for type hints, `pydantic` for defining data models, and `EmailStr` from `pydantic` for email validation.
@ -39,4 +38,4 @@ Explanation:
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.
Note: This file assumes that you have already set up the necessary dependencies and project structure for your FastAPI application. Make sure to import and use these schemas in the appropriate parts of your application, such as the API routes and database models.

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.middleware.cors import CORSMiddleware
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from app.api.db.database import engine, Base
from app.api.v1.routes import router
from app.api.core.middleware.activity_tracker import ActivityTrackerMiddleware
app = FastAPI()
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.
app.add_middleware(ActivityTrackerMiddleware)
app.include_router(router, prefix='/v1')
@app.on_event('startup')
def startup():
Base.metadata.create_all(bind=engine)

View File

@ -1,9 +1 @@
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.
Here's the `requirements.txt` file for the 'blog_app' FastAPI backend: