diff --git a/app/api/core/dependencies/dependencies.py b/app/api/core/dependencies/dependencies.py new file mode 100644 index 0000000..2263c5d --- /dev/null +++ b/app/api/core/dependencies/dependencies.py @@ -0,0 +1,13 @@ +from typing import Generator +from sqlalchemy.orm import Session +from app.api.db.database import SessionLocal +def get_db() -> Generator[Session, None, None]: + db = SessionLocal() + try: + yield db + finally: + db.close() +``` +This code defines a `get_db` function that returns a generator function. The generator function creates a new SQLAlchemy session using `SessionLocal` from `app.api.db.database` and yields the session. After the session is used, it is closed in the `finally` block. +The function signature `get_db() -> Generator[Session, None, None]` specifies that the function returns a generator that yields a `Session` object and does not receive or return any values. +This function is typically used as a dependency in FastAPI routes to provide a database session for querying and modifying data. \ No newline at end of file diff --git a/app/api/core/middleware/activity_tracker.py b/app/api/core/middleware/activity_tracker.py new file mode 100644 index 0000000..c76bd21 --- /dev/null +++ b/app/api/core/middleware/activity_tracker.py @@ -0,0 +1,18 @@ +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() + request_method = request.method + request_url = str(request.url) + response: 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 +``` +This code defines an `ActivityTrackerMiddleware` class that inherits from `BaseHTTPMiddleware`. The `dispatch` method is overridden to log the request method, URL, and processing time for each incoming request. +Here's a breakdown of the code: +This middleware can be added to the FastAPI application by including it in the list of middleware instances when creating the application instance. \ No newline at end of file diff --git a/app/api/db/database.py b/app/api/db/database.py new file mode 100644 index 0000000..d40c685 --- /dev/null +++ b/app/api/db/database.py @@ -0,0 +1,13 @@ +# app/api/db/database.py +from sqlalchemy import create_engine +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import sessionmaker +SQLALCHEMY_DATABASE_URL = "sqlite:///./blog_app.db" +engine = create_engine( + SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} +) +SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) +Base = declarative_base() +``` +This code defines the necessary components for working with a SQLite database using SQLAlchemy in a FastAPI application named "blog_app". +With this setup, you can define your database models by inheriting from `Base` and create database sessions using `SessionLocal`. The `engine` instance can be used for various database operations, such as creating tables or executing raw SQL queries. \ No newline at end of file diff --git a/app/api/v1/models/and.py b/app/api/v1/models/and.py new file mode 100644 index 0000000..0bd6b5b --- /dev/null +++ b/app/api/v1/models/and.py @@ -0,0 +1,11 @@ +from sqlalchemy import Column, Integer, String, ForeignKey +from sqlalchemy.orm import relationship +from app.api.db.database import Base +class And(Base): + __tablename__ = "ands" + id = Column(Integer, primary_key=True, index=True) + name = Column(String, nullable=False) + description = Column(String, nullable=True) + # Relationships + blog_id = Column(Integer, ForeignKey("blogs.id")) + blog = relationship("Blog", back_populates="ands") \ No newline at end of file diff --git a/app/api/v1/models/comments.py b/app/api/v1/models/comments.py new file mode 100644 index 0000000..f255d4a --- /dev/null +++ b/app/api/v1/models/comments.py @@ -0,0 +1,11 @@ +from sqlalchemy import Column, Integer, String, ForeignKey +from sqlalchemy.orm import relationship +from app.api.db.database import Base +class Comments(Base): + __tablename__ = "comments" + id = Column(Integer, primary_key=True, index=True) + content = Column(String) + post_id = Column(Integer, ForeignKey("posts.id")) + user_id = Column(Integer, ForeignKey("users.id")) + post = relationship("Post", back_populates="comments") + user = relationship("User", back_populates="comments") \ No newline at end of file diff --git a/app/api/v1/models/posts.py b/app/api/v1/models/posts.py new file mode 100644 index 0000000..c96e42a --- /dev/null +++ b/app/api/v1/models/posts.py @@ -0,0 +1,11 @@ +from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey +from sqlalchemy.orm import relationship +from app.api.db.database import Base +class Posts(Base): + __tablename__ = "posts" + id = Column(Integer, primary_key=True, index=True) + title = Column(String) + content = Column(Text) + published = Column(DateTime) + user_id = Column(Integer, ForeignKey("users.id")) + user = relationship("Users", back_populates="posts") \ No newline at end of file diff --git a/app/api/v1/models/user.py b/app/api/v1/models/user.py new file mode 100644 index 0000000..0060fb8 --- /dev/null +++ b/app/api/v1/models/user.py @@ -0,0 +1,11 @@ +# app/api/v1/models/user.py +from sqlalchemy import Column, Integer, String, Boolean +from app.api.db.database import Base +class User(Base): + __tablename__ = "users" + id = Column(Integer, primary_key=True, index=True) + username = Column(String, unique=True, index=True) + email = Column(String, unique=True, index=True) + password = Column(String) + is_active = Column(Boolean, default=True) + is_admin = Column(Boolean, default=False) \ No newline at end of file diff --git a/app/api/v1/routes/__init__.py b/app/api/v1/routes/__init__.py index e69de29..f2e95a4 100644 --- a/app/api/v1/routes/__init__.py +++ b/app/api/v1/routes/__init__.py @@ -0,0 +1,10 @@ +from fastapi import APIRouter +from .posts import router as posts_router +from .comments import router as comments_router +from .user import router as user_router +from .and import router as and_router +router = APIRouter() +router.include_router(posts_router, prefix="/posts", tags=["posts"]) +router.include_router(comments_router, prefix="/comments", tags=["comments"]) +router.include_router(user_router, prefix="/users", tags=["users"]) +router.include_router(and_router, prefix="/and", tags=["and"]) \ No newline at end of file diff --git a/app/api/v1/routes/and.py b/app/api/v1/routes/and.py new file mode 100644 index 0000000..6a756c3 --- /dev/null +++ b/app/api/v1/routes/and.py @@ -0,0 +1,24 @@ +from typing import List +from fastapi import APIRouter, Depends, HTTPException +from sqlalchemy.orm import Session +from app.api.core.dependencies.dependencies import get_db +from app.api.v1.models.and import And +from app.api.v1.schemas.and import AndCreate, AndRead +router = APIRouter() +@router.get("/ands", response_model=List[AndRead]) +def read_ands(db: Session = Depends(get_db)): + ands = db.query(And).all() + return ands +@router.post("/ands", response_model=AndRead) +def create_and(and_data: AndCreate, db: Session = Depends(get_db)): + and_obj = And(**and_data.dict()) + db.add(and_obj) + db.commit() + db.refresh(and_obj) + return and_obj +@router.get("/ands/{id}", response_model=AndRead) +def read_and(id: int, db: Session = Depends(get_db)): + and_obj = db.query(And).get(id) + if not and_obj: + raise HTTPException(status_code=404, detail="And not found") + return and_obj \ No newline at end of file diff --git a/app/api/v1/routes/comments.py b/app/api/v1/routes/comments.py new file mode 100644 index 0000000..40d9eed --- /dev/null +++ b/app/api/v1/routes/comments.py @@ -0,0 +1,24 @@ +from typing import List +from fastapi import APIRouter, Depends, HTTPException +from sqlalchemy.orm import Session +from app.api.v1.models.comments import Comments +from app.api.v1.schemas.comments import CommentsCreate, CommentsResponse +from app.api.core.dependencies.dependencies import get_db +router = APIRouter() +@router.get("/commentss", response_model=List[CommentsResponse]) +def read_commentss(db: Session = Depends(get_db)): + commentss = db.query(Comments).all() + return commentss +@router.post("/commentss", response_model=CommentsResponse) +def create_comments(comments: CommentsCreate, db: Session = Depends(get_db)): + db_comments = Comments(**comments.dict()) + db.add(db_comments) + db.commit() + db.refresh(db_comments) + return db_comments +@router.get("/commentss/{id}", response_model=CommentsResponse) +def read_comments(id: int, db: Session = Depends(get_db)): + db_comments = db.query(Comments).get(id) + if not db_comments: + raise HTTPException(status_code=404, detail="Comments not found") + return db_comments \ No newline at end of file diff --git a/app/api/v1/routes/posts.py b/app/api/v1/routes/posts.py new file mode 100644 index 0000000..0bce50d --- /dev/null +++ b/app/api/v1/routes/posts.py @@ -0,0 +1,24 @@ +from typing import List +from fastapi import APIRouter, Depends, HTTPException +from sqlalchemy.orm import Session +from app.api.v1.models.posts import Posts +from app.api.v1.schemas.posts import PostsCreate, PostsResponse +from app.api.core.dependencies.dependencies import get_db +router = APIRouter() +@router.get("/postss", response_model=List[PostsResponse]) +def read_postss(db: Session = Depends(get_db)): + postss = db.query(Posts).all() + return postss +@router.post("/postss", response_model=PostsResponse) +def create_posts(posts: PostsCreate, db: Session = Depends(get_db)): + db_posts = Posts(**posts.dict()) + db.add(db_posts) + db.commit() + db.refresh(db_posts) + return db_posts +@router.get("/postss/{id}", response_model=PostsResponse) +def read_posts(id: int, db: Session = Depends(get_db)): + posts = db.query(Posts).get(id) + if not posts: + raise HTTPException(status_code=404, detail="Posts not found") + return posts \ No newline at end of file diff --git a/app/api/v1/routes/user.py b/app/api/v1/routes/user.py new file mode 100644 index 0000000..6136cf3 --- /dev/null +++ b/app/api/v1/routes/user.py @@ -0,0 +1,24 @@ +from typing import List +from fastapi import APIRouter, Depends, HTTPException +from sqlalchemy.orm import Session +from app.api.v1.models.user import User +from app.api.v1.schemas.user import UserCreate, UserRead +from app.api.core.dependencies.dependencies import get_db +router = APIRouter() +@router.get("/users", response_model=List[UserRead]) +def read_users(db: Session = Depends(get_db)): + users = db.query(User).all() + return users +@router.post("/users", response_model=UserRead) +def create_user(user: UserCreate, db: Session = Depends(get_db)): + db_user = User(**user.dict()) + db.add(db_user) + db.commit() + db.refresh(db_user) + return db_user +@router.get("/users/{user_id}", response_model=UserRead) +def read_user(user_id: int, db: Session = Depends(get_db)): + db_user = db.query(User).filter(User.id == user_id).first() + if not db_user: + raise HTTPException(status_code=404, detail="User not found") + return db_user \ No newline at end of file diff --git a/app/api/v1/schemas/and.py b/app/api/v1/schemas/and.py new file mode 100644 index 0000000..ab15949 --- /dev/null +++ b/app/api/v1/schemas/and.py @@ -0,0 +1,13 @@ +from typing import Optional +from pydantic import BaseModel +# AndCreate Schema +class AndCreate(BaseModel): + title: str + body: str +# And Schema +class And(AndCreate): + id: int + is_published: bool + rating: Optional[int] = None + class Config: + orm_mode = True \ No newline at end of file diff --git a/app/api/v1/schemas/comments.py b/app/api/v1/schemas/comments.py new file mode 100644 index 0000000..ae68704 --- /dev/null +++ b/app/api/v1/schemas/comments.py @@ -0,0 +1,14 @@ +from typing import Optional +from datetime import datetime +from pydantic import BaseModel +class CommentsBase(BaseModel): + body: str + post_id: int +class CommentsCreate(CommentsBase): + pass +class Comments(CommentsBase): + id: int + created_at: datetime + updated_at: Optional[datetime] = None + class Config: + orm_mode = True \ No newline at end of file diff --git a/app/api/v1/schemas/posts.py b/app/api/v1/schemas/posts.py new file mode 100644 index 0000000..5a1766d --- /dev/null +++ b/app/api/v1/schemas/posts.py @@ -0,0 +1,18 @@ +from typing import Optional +from datetime import datetime +from pydantic import BaseModel +class PostsCreate(BaseModel): + title: str + content: str + published: bool = True + author_id: int +class Posts(BaseModel): + id: int + title: str + content: str + published: bool + created_at: datetime + updated_at: Optional[datetime] = None + author_id: int + class Config: + orm_mode = True \ No newline at end of file diff --git a/app/api/v1/schemas/user.py b/app/api/v1/schemas/user.py new file mode 100644 index 0000000..6c9d898 --- /dev/null +++ b/app/api/v1/schemas/user.py @@ -0,0 +1,16 @@ +from typing import Optional +from pydantic import BaseModel, EmailStr +# User Pydantic models +class UserBase(BaseModel): + email: Optional[EmailStr] = None + is_active: Optional[bool] = True + is_superuser: bool = False + full_name: Optional[str] = None +class UserCreate(UserBase): + email: EmailStr + password: str +class User(UserBase): + id: int + disabled: bool = False + class Config: + orm_mode = True \ No newline at end of file diff --git a/main.py b/main.py index dca5c44..9ed70aa 100644 --- a/main.py +++ b/main.py @@ -1,7 +1,11 @@ from fastapi import FastAPI - -app = FastAPI(title="Generated Backend") - -@app.get("/") -def read_root(): - return {"message": "Welcome to the generated backend"} \ No newline at end of file +from app.api.db.database import Base, engine +from app.api.v1.routes import router as v1_router +from app.api.core.middleware.activity_tracker import ActivityTrackerMiddleware +app = FastAPI() +# Create tables +Base.metadata.create_all(bind=engine) +# Include v1 router +app.include_router(v1_router, prefix="/v1") +# Add middleware +app.add_middleware(ActivityTrackerMiddleware) \ No newline at end of file