Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified blog.db
Binary file not shown.
1 change: 1 addition & 0 deletions blog/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@
SessionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=False)
Base = declarative_base()

"""now we have created Base this is used to created table"""
7 changes: 7 additions & 0 deletions blog/hasing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from passlib.context import CryptContext

pwd_cxt = CryptContext(schemes=["bcrypt"], deprecated="auto")

class Hash():
def bcrypt(password: str):
return pwd_cxt.hash(password)
45 changes: 34 additions & 11 deletions blog/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@
from . import schemas, models
from .database import engine, SessionLocal
from sqlalchemy.orm import Session

from typing import List
from .hasing import Hash
# from . import models
# dot represent importing schemas file from same directory


app = FastAPI()
models.Base.metadata.create_all(engine)
models.Base.metadata.create_all(engine) # this is related to creating table


def get_db():
Expand All @@ -19,13 +20,20 @@ def get_db():
db.close()


"""here you can see that we have invoked request: schemas.Blog from schemas
file so that title and attributes are used"""


@app.post('/blog', status_code=status.HTTP_201_CREATED)
def create(request: schemas.Blog, db: Session = Depends(get_db)):
new_blog = models.Blog(title=request.title, body=request.body)
db.add(new_blog)
db.commit()
db.refresh(new_blog)
return new_blog
new_blog = models.Blog(title=request.title, body=request.body) # this whole part is used to create table
db.add(new_blog) #
db.commit() #
db.refresh(new_blog) #
return new_blog #


# in delete we didn't used request because while deleting table schemas is not required


@app.delete('/blog/{id}', status_code=status.HTTP_204_NO_CONTENT)
Expand All @@ -36,25 +44,28 @@ def destroy(id, db: Session = Depends(get_db)):


# we require request:schemas.Blog because if you remove that you won't get parameter in put that is title and body
# db.query(models.Blog).filter(models.Blog.id == id).update({'title': 'updated title'}) this for only updating title
# db.query(models.Blog).filter(models.Blog.id == id).update({'title': 'updated title'}) this for only updating title
@app.put('/blog/{id}', status_code=status.HTTP_202_ACCEPTED)
def update(id, request: schemas.Blog, db: Session = Depends(get_db)):
blog = db.query(models.Blog).filter(models.Blog.id == id)
if not blog.first():
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'Blog with id {id} not found')
blog.update(request)
blog.update({'title': request.title, 'body': request.body})
db.commit()
return 'updated successfully'


"""here we are using list because set of data is going to represent that's why we have used list"""


@app.get('/blog')
@app.get('/blog', response_model=List[schemas.showBlog])
def all(db: Session = Depends(get_db)):
blogs = db.query(models.Blog).all()
# here we didnt used commit because we just seeing the content not modifying in content
return blogs


@app.get('/blog/{id}', status_code=200) # default status code as 200
@app.get('/blog/{id}', status_code=200, response_model=schemas.showBlog) # default status code as 200
def show(id, response: Response, db: Session = Depends(get_db)):
blog = db.query(models.Blog).filter(models.Blog.id == id).first()
if not blog:
Expand All @@ -63,3 +74,15 @@ def show(id, response: Response, db: Session = Depends(get_db)):
# response.status_code = status.HTTP_404_NOT_FOUND
# return {'details': f'Blog with the id {id} is not available'}
return blog




@app.post('/user')
def create_user(request: schemas.User, db: Session = Depends(get_db)):

new_user = models.User(name=request.name, email=request.email, password=Hash.bcrypt(request.password))
db.add(new_user)
db.commit()
db.refresh(new_user)
return new_user
12 changes: 11 additions & 1 deletion blog/models.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,20 @@
from sqlalchemy import Column, Integer, String
from .database import Base

"""this Base is from database connection that is from database.py"""


class Blog(Base):
__tablename__ = 'blogs'

id = Column(Integer, primary_key=True, index=True)
id = Column(Integer, primary_key=True, index=True) # id will be generated automatically
title = Column(String)
body = Column(String)


class User(Base): # base means database
__tablename__ = 'user'
id = Column(Integer, primary_key=True, index=True)
name = Column(String)
email = Column(String)
password = Column(String)
30 changes: 30 additions & 0 deletions blog/schemas.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,36 @@
"""in this schemas file we will have our basemodel and it can be extended to anyother files
for example if you want to extend basemodel to main.py file first you have to import and then invoke schemas.Blog
here this Blog refer to basemodel"""

from pydantic import BaseModel


class Blog(BaseModel):
title: str
body: str


"""this below class is used when you want to show the details of both
value present in Blog class so we extend that class"""
# class showBlog(Blog):
# class Config():
# orm_mode = True

"""If you want to change the representation of dteails different form Blog class so you have to extend
BaseModel and in that class you have to mention the argument which you wanted to reprent"""


class showBlog(BaseModel):
title: str

class Config():
orm_mode = True


"""orm is used because we have used db.query which is belongs to sqlalchemy.orm"""


class User(BaseModel):
name:str
email:str
password:str
26 changes: 26 additions & 0 deletions register.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from fastapi import FastAPI
# from pydantic import BaseModel

app = FastAPI()

signupdb = []


class Login():
username: str
password: str
email: str
phone: int


@app.get('/User')
def show():
return {'details': signupdb}


@app.post('/User/{id}')
def add_user(request: Login):
signupdb.append(request.dict())
return signupdb[-1]


5 changes: 3 additions & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@

fastapi

uvicorn
sqlalchemy
sqlalchemy
passlib
bcrypt
62 changes: 62 additions & 0 deletions test-1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
# from typing import Optional

app = FastAPI()

origins = [
"http://localhost",
"http://localhost:8080",
]

app.add_middleware(
CORSMiddleware,
allow_origins=['*'],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

class User(BaseModel):
name: str
userid: str
phone: str


users = []
userids = []


def doesuserexist(user: str):
for x in range(len(users)):
if users[x] == user:
return True
else:
return False


@app.post('/login')
def login(user: User):
res = {"response": "error"}
for x in range(len(users)):
if users[x] == user.name:
if userids[x] == user.userid:
res = {"response": "success"}
else:
res = {"response": "Incorrect userid"}
else:
res = {"response": "Incorrect name"}
return res


@app.post('/register')
def register(user: User):
res = {"response": "error"}
if not(doesuserexist(user.name)):
users.append(user.name)
userids.append(user.userid)
res = {"response": "success"}
else:
res = {"response": "user already exists"}
return res