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

@ -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.orm import relationship
@ -9,24 +10,15 @@ 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)
content = Column(Text, nullable=False)
author = Column(String, nullable=False)
post_id = Column(Integer, ForeignKey("posts.id"), nullable=False)
user = relationship("User", back_populates="comments")
post = relationship("Post", back_populates="comments")
def __repr__(self):
return f"Comment(id={self.id}, text='{self.text[:20]}...', user_id={self.user_id}, post_id={self.post_id})"
return f"Comment(id={self.id}, content='{self.content[:20]}...', author='{self.author}', post_id={self.post_id})"
Explanation:
1. We import the necessary modules from SQLAlchemy: `Column`, `ForeignKey`, `Integer`, `String`, `Text`, and `relationship`.
5. We define the columns for the `Comment` model:
- `id`: an integer primary key and index column.
- `text`: a text column for the comment content, which is required (`nullable=False`).
- `user_id`: an integer foreign key column referring to the `users` table, which is required (`nullable=False`).
- `post_id`: an integer foreign key column referring to the `posts` table, which is required (`nullable=False`).
6. We define the relationships between the `Comment` model and the `User` and `Post` models using the `relationship` function from SQLAlchemy:
- `user`: a one-to-many relationship with the `User` model, using the `back_populates` parameter to enable bi-directional access.
- `post`: a one-to-many relationship with the `Post` model, using the `back_populates` parameter to enable bi-directional access.
5. The `content` column stores the text content of the comment and is required (`nullable=False`).

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, 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
from app.db import Base
@ -12,26 +9,20 @@ class Post(Base):
__tablename__ = "posts"
id = Column(Integer, primary_key=True, index=True)
title = Column(String, nullable=False)
content = Column(Text, nullable=False)
created_at = Column(TIMESTAMP, server_default=func.now())
updated_at = Column(TIMESTAMP, server_default=func.now(), onupdate=func.now())
user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
title = Column(String, index=True)
content = Column(Text)
user_id = Column(Integer, ForeignKey("users.id"))
user = relationship("User", back_populates="posts")
author = relationship("User", back_populates="posts")
def __repr__(self):
return f"Post(id={self.id}, title='{self.title}', content='{self.content[:20]}...')"
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:
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.
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.
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 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)
description = Column(String, nullable=True)
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 app.db import Base
@ -14,12 +15,17 @@ class User(Base):
is_superuser = Column(Boolean, default=False)
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:
- `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`).
Explanation:
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 .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,17 @@
Here's the `comments.py` file with CRUD endpoints for comments:
from typing import List
from fastapi import APIRouter, Depends, HTTPException
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
from app.models.comment import Comment
from app.schemas.comment import CommentCreate, CommentResponse
router = APIRouter(
prefix="/comments",
tags=["Comments"],
router = APIRouter()
@router.post("/comments", response_model=CommentResponse, status_code=201)
@router.post("/", response_model=CommentResponse)
def create_comment(comment: CommentCreate, db: Session = Depends(get_db)):
db_comment = Comment(**comment.dict())
db.add(db_comment)
@ -16,19 +19,19 @@ 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:
@ -40,22 +43,13 @@ def update_comment(comment_id: int, comment: CommentCreate, db: Session = Depend
db.refresh(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)):
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 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:
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,14 +1,18 @@
Here's the `posts.py` file with CRUD endpoints for posts:
from typing import List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.db import get_db
from app.models import Post
from app.schemas import PostCreate, PostResponse
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)):
new_post = Post(**post.dict())
db.add(new_post)
@ -16,31 +20,30 @@ def create_post(post: PostCreate, db: Session = Depends(get_db)):
db.refresh(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)):
posts = db.query(Post).all()
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)):
post = db.query(Post).filter(Post.id == post_id).first()
if not post:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Post not found")
return post
@router.put("/posts/{post_id}", response_model=PostResponse)
@router.put("/{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():
for key, value in post.dict().items():
setattr(db_post, key, value)
db.commit()
db.refresh(db_post)
return db_post
@router.delete("/posts/{post_id}", status_code=status.HTTP_204_NO_CONTENT)
@router.delete("/{post_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_post(post_id: int, db: Session = Depends(get_db)):
post = db.query(Post).filter(Post.id == post_id).first()
if not post:
@ -52,7 +55,5 @@ def delete_post(post_id: int, db: Session = Depends(get_db)):
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 you have the `Post` model, `PostCreate` and `PostResponse` schemas, and the `get_db` dependency defined in your project.

View File

@ -3,7 +3,7 @@ from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.db.session import get_db
from app.models.tag import Tag
from app.models import Tag
from app.schemas.tag import TagCreate, TagUpdate, TagOut
router = APIRouter()
@ -50,8 +50,11 @@ def delete_tag(tag_id: int, db: Session = Depends(get_db)):
db.commit()
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 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.core.security import get_current_user
from app.db.session import get_db
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])
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=UserRead)
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.commit()
db.refresh(db_user)
return db_user
@router.put("/users/{user_id}", response_model=User)
def update_user(user_id: int, user: UserUpdate, db: Session = Depends(get_db)):
db_user = db.query(UserModel).get(user_id)
@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
@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:
raise HTTPException(status_code=404, detail="User not found")
update_data = user.dict(exclude_unset=True)
for key, value in update_data.items():
return db_user
@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)
db.add(db_user)
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)
@router.delete("/{user_id}", response_model=UserRead)
def delete_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:
raise HTTPException(status_code=404, detail="User not found")
db.delete(db_user)
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 typing import Optional
from pydantic import BaseModel, Field
from app.db.base_class import Base
class CommentBase(BaseModel):
content: str = Field(..., min_length=1, max_length=500)
content: str = Field(..., min_length=1, max_length=1000)
class CommentCreate(CommentBase):
pass
@ -17,9 +18,9 @@ class CommentUpdate(CommentBase):
class CommentInDBBase(CommentBase):
id: int
post_id: int
created_at: datetime
updated_at: Optional[datetime] = None
post_id: int
class Config:
orm_mode = True
@ -30,11 +31,13 @@ class Comment(CommentInDBBase):
class CommentInDB(CommentInDBBase):
pass
Explanation:
1. We import the necessary modules: `datetime` for working with dates and times, `typing` for type hints, and `pydantic` for defining data models.
This file defines the following Pydantic models for comments:
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 pydantic import BaseModel
from datetime import datetime
class PostBase(BaseModel):
class PostCreate(BaseModel):
title: str
content: str
class PostCreate(PostBase):
pass
class PostUpdate(PostBase):
pass
class PostInDBBase(PostBase):
class PostRead(BaseModel):
id: int
title: str
content: str
created_at: datetime
updated_at: Optional[datetime] = None
class Config:
orm_mode = True
class Post(PostInDBBase):
pass
class PostList(BaseModel):
__root__: list[Post]
class PostUpdate(BaseModel):
title: Optional[str] = None
content: Optional[str] = None
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`.
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.
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.
Note: Make sure to import the necessary dependencies (`typing`, `pydantic`, and `datetime`) at the top of the file.

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 pydantic import BaseModel
@ -9,22 +7,21 @@ class TagBase(BaseModel):
class TagCreate(TagBase):
pass
class TagUpdate(TagBase):
pass
class TagUpdate(BaseModel):
name: Optional[str] = None
class TagInDBBase(TagBase):
class TagResponse(TagBase):
id: int
name: str
class Config:
orm_mode = True
class Tag(TagInDBBase):
pass
This file defines the following Pydantic schemas for tags:
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 pydantic import BaseModel, EmailStr
class UserBase(BaseModel):
email: Optional[EmailStr] = None
email: EmailStr
is_active: Optional[bool] = True
is_superuser: bool = False
is_superuser: Optional[bool] = False
full_name: Optional[str] = None
class UserCreate(UserBase):
email: EmailStr
password: str
class UserUpdate(UserBase):
password: Optional[str] = None
class UserInDBBase(UserBase):
id: Optional[int] = None
class User(UserBase):
id: int
class Config:
orm_mode = True
class User(UserInDBBase):
pass
class UserInDB(UserInDBBase):
hashed_password: str
Explanation:
1. We import the necessary modules: `typing` for type hints, and `pydantic` for defining data models.
This file defines the following Pydantic schemas:
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: Make sure to import the necessary dependencies, such as `pydantic` and `typing`, at the top of the file.

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,5 @@
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.
fastapi
uvicorn
sqlalchemy
pydantic
loguru