├── blog ├── __init__.py ├── routers │ ├── __init__.py │ ├── user.py │ ├── authentication.py │ └── blog.py ├── hashing.py ├── main.py ├── oauth2.py ├── database.py ├── repository │ ├── user.py │ └── blog.py ├── models.py ├── schemas.py └── token.py ├── app ├── blog │ ├── __init__.py │ ├── routers │ │ ├── __init__.py │ │ ├── user.py │ │ ├── authentication.py │ │ └── blog.py │ ├── hashing.py │ ├── oauth2.py │ ├── database.py │ ├── models.py │ ├── repository │ │ ├── user.py │ │ └── blog.py │ ├── schemas.py │ └── token.py ├── blog.db ├── requirements.txt └── main.py ├── blog.db ├── requirements.txt ├── __pycache__ ├── main.cpython-39.pyc ├── mymain.cpython-39.pyc └── bitfumes.cpython-39.pyc ├── .gitignore └── main.py /blog/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /app/blog/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /app/blog/routers/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /blog/routers/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /blog.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rohanmistry231/FastAPI-Learning/main/blog.db -------------------------------------------------------------------------------- /app/blog.db: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rohanmistry231/FastAPI-Learning/main/app/blog.db -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | fastapi 2 | uvicorn 3 | sqlalchemy 4 | passlib 5 | bcrypt 6 | python-jose 7 | python-multipart -------------------------------------------------------------------------------- /app/requirements.txt: -------------------------------------------------------------------------------- 1 | fastapi 2 | uvicorn 3 | sqlalchemy 4 | passlib 5 | bcrypt 6 | python-jose 7 | python-multipart -------------------------------------------------------------------------------- /__pycache__/main.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rohanmistry231/FastAPI-Learning/main/__pycache__/main.cpython-39.pyc -------------------------------------------------------------------------------- /__pycache__/mymain.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rohanmistry231/FastAPI-Learning/main/__pycache__/mymain.cpython-39.pyc -------------------------------------------------------------------------------- /__pycache__/bitfumes.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rohanmistry231/FastAPI-Learning/main/__pycache__/bitfumes.cpython-39.pyc -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | fastapi-env 3 | blog-env 4 | blog/__pycache__ 5 | .DS_Store 6 | .vscode 7 | .gitignore 8 | app/.deta 9 | app/blog/__pycache__ 10 | -------------------------------------------------------------------------------- /app/blog/hashing.py: -------------------------------------------------------------------------------- 1 | from passlib.context import CryptContext 2 | 3 | pwd_cxt = CryptContext(schemes=["bcrypt"], deprecated="auto") 4 | 5 | class Hash(): 6 | def bcrypt(password: str): 7 | return pwd_cxt.hash(password) 8 | 9 | def verify(hashed_password,plain_password): 10 | return pwd_cxt.verify(plain_password,hashed_password) -------------------------------------------------------------------------------- /blog/hashing.py: -------------------------------------------------------------------------------- 1 | from passlib.context import CryptContext 2 | 3 | pwd_cxt = CryptContext(schemes=["bcrypt"], deprecated="auto") 4 | 5 | class Hash(): 6 | def bcrypt(password: str): 7 | return pwd_cxt.hash(password) 8 | 9 | def verify(hashed_password,plain_password): 10 | return pwd_cxt.verify(plain_password,hashed_password) -------------------------------------------------------------------------------- /blog/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI 2 | from . import models 3 | from .database import engine 4 | from .routers import blog, user, authentication 5 | 6 | app = FastAPI() 7 | 8 | models.Base.metadata.create_all(engine) 9 | 10 | app.include_router(authentication.router) 11 | app.include_router(blog.router) 12 | app.include_router(user.router) 13 | -------------------------------------------------------------------------------- /app/main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI 2 | from blog import models 3 | from blog.database import engine 4 | from blog.routers import blog, user, authentication 5 | 6 | app = FastAPI() 7 | 8 | models.Base.metadata.create_all(engine) 9 | 10 | app.include_router(authentication.router) 11 | app.include_router(blog.router) 12 | app.include_router(user.router) 13 | -------------------------------------------------------------------------------- /blog/oauth2.py: -------------------------------------------------------------------------------- 1 | from fastapi import Depends, HTTPException, status 2 | from fastapi.security import OAuth2PasswordBearer 3 | from . import token 4 | 5 | oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login") 6 | 7 | def get_current_user(data: str = Depends(oauth2_scheme)): 8 | credentials_exception = HTTPException( 9 | status_code=status.HTTP_401_UNAUTHORIZED, 10 | detail="Could not validate credentials", 11 | headers={"WWW-Authenticate": "Bearer"}, 12 | ) 13 | 14 | return token.verify_token(data, credentials_exception) 15 | -------------------------------------------------------------------------------- /app/blog/oauth2.py: -------------------------------------------------------------------------------- 1 | from fastapi import Depends, HTTPException, status 2 | from fastapi.security import OAuth2PasswordBearer 3 | from blog import token 4 | 5 | oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login") 6 | 7 | 8 | def get_current_user(data: str = Depends(oauth2_scheme)): 9 | credentials_exception = HTTPException( 10 | status_code=status.HTTP_401_UNAUTHORIZED, 11 | detail="Could not validate credentials", 12 | headers={"WWW-Authenticate": "Bearer"}, 13 | ) 14 | 15 | return token.verify_token(data, credentials_exception) 16 | -------------------------------------------------------------------------------- /blog/database.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import create_engine 2 | from sqlalchemy.ext.declarative import declarative_base 3 | from sqlalchemy.orm import sessionmaker 4 | 5 | SQLALCHAMY_DATABASE_URL = 'sqlite:///./blog.db' 6 | 7 | engine = create_engine(SQLALCHAMY_DATABASE_URL, connect_args={ 8 | "check_same_thread": False}) 9 | 10 | SessionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=False,) 11 | 12 | Base = declarative_base() 13 | 14 | def get_db(): 15 | db = SessionLocal() 16 | try: 17 | yield db 18 | finally: 19 | db.close() -------------------------------------------------------------------------------- /app/blog/database.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import create_engine 2 | from sqlalchemy.ext.declarative import declarative_base 3 | from sqlalchemy.orm import sessionmaker 4 | 5 | SQLALCHAMY_DATABASE_URL = 'sqlite:///./blog.db' 6 | 7 | engine = create_engine(SQLALCHAMY_DATABASE_URL, connect_args={ 8 | "check_same_thread": False}) 9 | 10 | SessionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=False,) 11 | 12 | Base = declarative_base() 13 | 14 | def get_db(): 15 | db = SessionLocal() 16 | try: 17 | yield db 18 | finally: 19 | db.close() -------------------------------------------------------------------------------- /blog/routers/user.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter 2 | from .. import database, schemas, models 3 | from sqlalchemy.orm import Session 4 | from fastapi import APIRouter,Depends,status 5 | from ..repository import user 6 | 7 | router = APIRouter( 8 | prefix="/user", 9 | tags=['Users'] 10 | ) 11 | 12 | get_db = database.get_db 13 | 14 | 15 | @router.post('/', response_model=schemas.ShowUser) 16 | def create_user(request: schemas.User,db: Session = Depends(get_db)): 17 | return user.create(request,db) 18 | 19 | @router.get('/{id}',response_model=schemas.ShowUser) 20 | def get_user(id:int,db: Session = Depends(get_db)): 21 | return user.show(id,db) 22 | -------------------------------------------------------------------------------- /app/blog/routers/user.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter 2 | from blog import database, schemas, models 3 | from sqlalchemy.orm import Session 4 | from fastapi import APIRouter, Depends, status 5 | from blog.repository import user 6 | 7 | router = APIRouter( 8 | prefix="/user", 9 | tags=['Users'] 10 | ) 11 | 12 | get_db = database.get_db 13 | 14 | 15 | @router.post('/', response_model=schemas.ShowUser) 16 | def create_user(request: schemas.User, db: Session = Depends(get_db)): 17 | return user.create(request, db) 18 | 19 | 20 | @router.get('/{id}', response_model=schemas.ShowUser) 21 | def get_user(id: int, db: Session = Depends(get_db)): 22 | return user.show(id, db) 23 | -------------------------------------------------------------------------------- /blog/repository/user.py: -------------------------------------------------------------------------------- 1 | 2 | from sqlalchemy.orm import Session 3 | from .. import models, schemas 4 | from fastapi import HTTPException,status 5 | from ..hashing import Hash 6 | 7 | def create(request: schemas.User,db:Session): 8 | new_user = models.User(name=request.name,email=request.email,password=Hash.bcrypt(request.password)) 9 | db.add(new_user) 10 | db.commit() 11 | db.refresh(new_user) 12 | return new_user 13 | 14 | def show(id:int,db:Session): 15 | user = db.query(models.User).filter(models.User.id == id).first() 16 | if not user: 17 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, 18 | detail=f"User with the id {id} is not available") 19 | return user -------------------------------------------------------------------------------- /blog/models.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import Column, Integer, String, ForeignKey 2 | from .database import Base 3 | from sqlalchemy.orm import relationship 4 | 5 | 6 | class Blog(Base): 7 | __tablename__ = 'blogs' 8 | 9 | id = Column(Integer, primary_key=True, index=True) 10 | title = Column(String) 11 | body = Column(String) 12 | user_id = Column(Integer, ForeignKey('users.id')) 13 | 14 | creator = relationship("User", back_populates="blogs") 15 | 16 | 17 | class User(Base): 18 | __tablename__ = 'users' 19 | 20 | id = Column(Integer, primary_key=True, index=True) 21 | name = Column(String) 22 | email = Column(String) 23 | password = Column(String) 24 | 25 | blogs = relationship('Blog', back_populates="creator") 26 | -------------------------------------------------------------------------------- /app/blog/models.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy import Column, Integer, String, ForeignKey 2 | from blog.database import Base 3 | from sqlalchemy.orm import relationship 4 | 5 | 6 | class Blog(Base): 7 | __tablename__ = 'blogs' 8 | 9 | id = Column(Integer, primary_key=True, index=True) 10 | title = Column(String) 11 | body = Column(String) 12 | user_id = Column(Integer, ForeignKey('users.id')) 13 | 14 | creator = relationship("User", back_populates="blogs") 15 | 16 | 17 | class User(Base): 18 | __tablename__ = 'users' 19 | 20 | id = Column(Integer, primary_key=True, index=True) 21 | name = Column(String) 22 | email = Column(String) 23 | password = Column(String) 24 | 25 | blogs = relationship('Blog', back_populates="creator") 26 | -------------------------------------------------------------------------------- /app/blog/repository/user.py: -------------------------------------------------------------------------------- 1 | 2 | from sqlalchemy.orm import Session 3 | from blog import models, schemas 4 | from fastapi import HTTPException, status 5 | from blog.hashing import Hash 6 | 7 | 8 | def create(request: schemas.User, db: Session): 9 | new_user = models.User( 10 | name=request.name, email=request.email, password=Hash.bcrypt(request.password)) 11 | db.add(new_user) 12 | db.commit() 13 | db.refresh(new_user) 14 | return new_user 15 | 16 | 17 | def show(id: int, db: Session): 18 | user = db.query(models.User).filter(models.User.id == id).first() 19 | if not user: 20 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, 21 | detail=f"User with the id {id} is not available") 22 | return user 23 | -------------------------------------------------------------------------------- /app/blog/schemas.py: -------------------------------------------------------------------------------- 1 | from typing import List, Optional 2 | from pydantic import BaseModel 3 | 4 | 5 | class BlogBase(BaseModel): 6 | title: str 7 | body: str 8 | 9 | class Blog(BlogBase): 10 | class Config(): 11 | orm_mode = True 12 | 13 | class User(BaseModel): 14 | name:str 15 | email:str 16 | password:str 17 | 18 | class ShowUser(BaseModel): 19 | name:str 20 | email:str 21 | blogs : List[Blog] =[] 22 | class Config(): 23 | orm_mode = True 24 | 25 | class ShowBlog(BaseModel): 26 | title: str 27 | body:str 28 | creator: ShowUser 29 | 30 | class Config(): 31 | orm_mode = True 32 | 33 | 34 | class Login(BaseModel): 35 | username: str 36 | password:str 37 | 38 | 39 | class Token(BaseModel): 40 | access_token: str 41 | token_type: str 42 | 43 | 44 | class TokenData(BaseModel): 45 | email: Optional[str] = None 46 | -------------------------------------------------------------------------------- /blog/schemas.py: -------------------------------------------------------------------------------- 1 | from typing import List, Optional 2 | from pydantic import BaseModel 3 | 4 | 5 | class BlogBase(BaseModel): 6 | title: str 7 | body: str 8 | 9 | class Blog(BlogBase): 10 | class Config(): 11 | orm_mode = True 12 | 13 | class User(BaseModel): 14 | name:str 15 | email:str 16 | password:str 17 | 18 | class ShowUser(BaseModel): 19 | name:str 20 | email:str 21 | blogs : List[Blog] =[] 22 | class Config(): 23 | orm_mode = True 24 | 25 | class ShowBlog(BaseModel): 26 | title: str 27 | body:str 28 | creator: ShowUser 29 | 30 | class Config(): 31 | orm_mode = True 32 | 33 | 34 | class Login(BaseModel): 35 | username: str 36 | password:str 37 | 38 | 39 | class Token(BaseModel): 40 | access_token: str 41 | token_type: str 42 | 43 | 44 | class TokenData(BaseModel): 45 | email: Optional[str] = None 46 | -------------------------------------------------------------------------------- /blog/token.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime, timedelta 2 | from jose import JWTError, jwt 3 | from . import schemas 4 | 5 | SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7" 6 | ALGORITHM = "HS256" 7 | ACCESS_TOKEN_EXPIRE_MINUTES = 30 8 | 9 | def create_access_token(data: dict): 10 | to_encode = data.copy() 11 | expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) 12 | to_encode.update({"exp": expire}) 13 | encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) 14 | return encoded_jwt 15 | 16 | def verify_token(token:str,credentials_exception): 17 | try: 18 | payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) 19 | email: str = payload.get("sub") 20 | if email is None: 21 | raise credentials_exception 22 | token_data = schemas.TokenData(email=email) 23 | except JWTError: 24 | raise credentials_exception -------------------------------------------------------------------------------- /app/blog/token.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime, timedelta 2 | from jose import JWTError, jwt 3 | from blog import schemas 4 | 5 | SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7" 6 | ALGORITHM = "HS256" 7 | ACCESS_TOKEN_EXPIRE_MINUTES = 30 8 | 9 | 10 | def create_access_token(data: dict): 11 | to_encode = data.copy() 12 | expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) 13 | to_encode.update({"exp": expire}) 14 | encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) 15 | return encoded_jwt 16 | 17 | 18 | def verify_token(token: str, credentials_exception): 19 | try: 20 | payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) 21 | email: str = payload.get("sub") 22 | if email is None: 23 | raise credentials_exception 24 | token_data = schemas.TokenData(email=email) 25 | except JWTError: 26 | raise credentials_exception 27 | -------------------------------------------------------------------------------- /blog/routers/authentication.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Depends, status, HTTPException 2 | from fastapi.security import OAuth2PasswordRequestForm 3 | from .. import schemas, database, models, token 4 | from ..hashing import Hash 5 | from sqlalchemy.orm import Session 6 | router = APIRouter(tags=['Authentication']) 7 | 8 | @router.post('/login') 9 | def login(request:OAuth2PasswordRequestForm = Depends(), db: Session = Depends(database.get_db)): 10 | user = db.query(models.User).filter(models.User.email == request.username).first() 11 | if not user: 12 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, 13 | detail=f"Invalid Credentials") 14 | if not Hash.verify(user.password, request.password): 15 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, 16 | detail=f"Incorrect password") 17 | 18 | access_token = token.create_access_token(data={"sub": user.email}) 19 | return {"access_token": access_token, "token_type": "bearer"} -------------------------------------------------------------------------------- /app/blog/routers/authentication.py: -------------------------------------------------------------------------------- 1 | from fastapi import APIRouter, Depends, status, HTTPException 2 | from fastapi.security import OAuth2PasswordRequestForm 3 | from blog import schemas, database, models, token 4 | from blog.hashing import Hash 5 | from sqlalchemy.orm import Session 6 | 7 | router = APIRouter(tags=['Authentication']) 8 | 9 | 10 | @router.post('/login') 11 | def login(request: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(database.get_db)): 12 | user = db.query(models.User).filter( 13 | models.User.email == request.username).first() 14 | if not user: 15 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, 16 | detail=f"Invalid Credentials") 17 | if not Hash.verify(user.password, request.password): 18 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, 19 | detail=f"Incorrect password") 20 | 21 | access_token = token.create_access_token(data={"sub": user.email}) 22 | return {"access_token": access_token, "token_type": "bearer"} 23 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI 2 | from typing import Optional 3 | from pydantic import BaseModel 4 | 5 | 6 | app = FastAPI() 7 | 8 | 9 | @app.get('/blog') 10 | def index(limit=10, published: bool = True, sort: Optional[str] = None): 11 | # only get 10 published blogs 12 | if published: 13 | return {'data': f'{limit} published blogs from the db'} 14 | else: 15 | return {'data': f'{limit} blogs from the db'} 16 | 17 | 18 | @app.get('/blog/unpublished') 19 | def unpublished(): 20 | return {'data': 'all unpublished blogs'} 21 | 22 | 23 | @app.get('/blog/{id}') 24 | def show(id: int): 25 | # fetch blog with id = id 26 | return {'data': id} 27 | 28 | 29 | @app.get('/blog/{id}/comments') 30 | def comments(id, limit=10): 31 | # fetch comments of blog with id = id 32 | return {'data': {'1', '2'}} 33 | 34 | 35 | class Blog(BaseModel): 36 | title: str 37 | body: str 38 | published: Optional[bool] 39 | 40 | 41 | @app.post('/blog') 42 | def create_blog(blog: Blog): 43 | return {'data': f"Blog is created with title as {blog.title}"} 44 | -------------------------------------------------------------------------------- /blog/routers/blog.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | from fastapi import APIRouter,Depends,status,HTTPException 3 | from .. import schemas, database, models, oauth2 4 | from sqlalchemy.orm import Session 5 | from ..repository import blog 6 | 7 | router = APIRouter( 8 | prefix="/blog", 9 | tags=['Blogs'] 10 | ) 11 | 12 | get_db = database.get_db 13 | 14 | @router.get('/', response_model=List[schemas.ShowBlog]) 15 | def all(db: Session = Depends(get_db),current_user: schemas.User = Depends(oauth2.get_current_user)): 16 | return blog.get_all(db) 17 | 18 | 19 | @router.post('/', status_code=status.HTTP_201_CREATED,) 20 | def create(request: schemas.Blog, db: Session = Depends(get_db),current_user: schemas.User = Depends(oauth2.get_current_user)): 21 | return blog.create(request, db) 22 | 23 | @router.delete('/{id}', status_code=status.HTTP_204_NO_CONTENT) 24 | def destroy(id:int, db: Session = Depends(get_db),current_user: schemas.User = Depends(oauth2.get_current_user)): 25 | return blog.destroy(id,db) 26 | 27 | 28 | @router.put('/{id}', status_code=status.HTTP_202_ACCEPTED) 29 | def update(id:int, request: schemas.Blog, db: Session = Depends(get_db),current_user: schemas.User = Depends(oauth2.get_current_user)): 30 | return blog.update(id,request, db) 31 | 32 | 33 | @router.get('/{id}', status_code=200, response_model=schemas.ShowBlog) 34 | def show(id:int, db: Session = Depends(get_db),current_user: schemas.User = Depends(oauth2.get_current_user)): 35 | return blog.show(id,db) -------------------------------------------------------------------------------- /app/blog/routers/blog.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | from fastapi import APIRouter, Depends, status, HTTPException 3 | from blog import schemas, database, models, oauth2 4 | from sqlalchemy.orm import Session 5 | from blog.repository import blog 6 | 7 | router = APIRouter( 8 | prefix="/blog", 9 | tags=['Blogs'] 10 | ) 11 | 12 | get_db = database.get_db 13 | 14 | 15 | @router.get('/', response_model=List[schemas.ShowBlog]) 16 | def all(db: Session = Depends(get_db), current_user: schemas.User = Depends(oauth2.get_current_user)): 17 | return blog.get_all(db) 18 | 19 | 20 | @router.post('/', status_code=status.HTTP_201_CREATED,) 21 | def create(request: schemas.Blog, db: Session = Depends(get_db), current_user: schemas.User = Depends(oauth2.get_current_user)): 22 | return blog.create(request, db) 23 | 24 | 25 | @router.delete('/{id}', status_code=status.HTTP_204_NO_CONTENT) 26 | def destroy(id: int, db: Session = Depends(get_db), current_user: schemas.User = Depends(oauth2.get_current_user)): 27 | return blog.destroy(id, db) 28 | 29 | 30 | @router.put('/{id}', status_code=status.HTTP_202_ACCEPTED) 31 | def update(id: int, request: schemas.Blog, db: Session = Depends(get_db), current_user: schemas.User = Depends(oauth2.get_current_user)): 32 | return blog.update(id, request, db) 33 | 34 | 35 | @router.get('/{id}', status_code=200, response_model=schemas.ShowBlog) 36 | def show(id: int, db: Session = Depends(get_db), current_user: schemas.User = Depends(oauth2.get_current_user)): 37 | return blog.show(id, db) 38 | -------------------------------------------------------------------------------- /blog/repository/blog.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm import Session 2 | from .. import models, schemas 3 | from fastapi import HTTPException,status 4 | 5 | def get_all(db: Session): 6 | blogs = db.query(models.Blog).all() 7 | return blogs 8 | 9 | def create(request: schemas.Blog,db: Session): 10 | new_blog = models.Blog(title=request.title, body=request.body,user_id=1) 11 | db.add(new_blog) 12 | db.commit() 13 | db.refresh(new_blog) 14 | return new_blog 15 | 16 | def destroy(id:int,db: Session): 17 | blog = db.query(models.Blog).filter(models.Blog.id == id) 18 | 19 | if not blog.first(): 20 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, 21 | detail=f"Blog with id {id} not found") 22 | 23 | blog.delete(synchronize_session=False) 24 | db.commit() 25 | return 'done' 26 | 27 | def update(id:int,request:schemas.Blog, db:Session): 28 | blog = db.query(models.Blog).filter(models.Blog.id == id) 29 | 30 | if not blog.first(): 31 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, 32 | detail=f"Blog with id {id} not found") 33 | 34 | blog.update(request) 35 | db.commit() 36 | return 'updated' 37 | 38 | def show(id:int,db:Session): 39 | blog = db.query(models.Blog).filter(models.Blog.id == id).first() 40 | if not blog: 41 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, 42 | detail=f"Blog with the id {id} is not available") 43 | return blog -------------------------------------------------------------------------------- /app/blog/repository/blog.py: -------------------------------------------------------------------------------- 1 | from sqlalchemy.orm import Session 2 | from blog import models, schemas 3 | from fastapi import HTTPException, status 4 | 5 | 6 | def get_all(db: Session): 7 | blogs = db.query(models.Blog).all() 8 | return blogs 9 | 10 | 11 | def create(request: schemas.Blog, db: Session): 12 | new_blog = models.Blog(title=request.title, body=request.body, user_id=1) 13 | db.add(new_blog) 14 | db.commit() 15 | db.refresh(new_blog) 16 | return new_blog 17 | 18 | 19 | def destroy(id: int, db: Session): 20 | blog = db.query(models.Blog).filter(models.Blog.id == id) 21 | 22 | if not blog.first(): 23 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, 24 | detail=f"Blog with id {id} not found") 25 | 26 | blog.delete(synchronize_session=False) 27 | db.commit() 28 | return 'done' 29 | 30 | 31 | def update(id: int, request: schemas.Blog, db: Session): 32 | blog = db.query(models.Blog).filter(models.Blog.id == id) 33 | 34 | if not blog.first(): 35 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, 36 | detail=f"Blog with id {id} not found") 37 | 38 | blog.update(request) 39 | db.commit() 40 | return 'updated' 41 | 42 | 43 | def show(id: int, db: Session): 44 | blog = db.query(models.Blog).filter(models.Blog.id == id).first() 45 | if not blog: 46 | raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, 47 | detail=f"Blog with the id {id} is not available") 48 | return blog 49 | --------------------------------------------------------------------------------