chukwuyem

python

Oct 30th, 2020
95
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from typing import List
  2. from datetime import datetime, timedelta
  3. #from supertokens_fastapi import get_cors_allowed_headers
  4.  
  5.  
  6. from fastapi import Depends, FastAPI, HTTPException, Form
  7. from sqlalchemy.orm import Session
  8. from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
  9. from jose import JWTError, jwt
  10.  
  11. #from . import crud, models, schemas
  12.  
  13. import crud
  14.  
  15. import models
  16.  
  17. import schemas
  18. #from .database import SessionLocal, engine
  19. from database import SessionLocal, engine
  20. #from fastapi.middleware.cors import CORSMiddleware
  21. from starlette.middleware.cors import CORSMiddleware
  22.  
  23.  
  24.  
  25.  
  26. models.Base.metadata.create_all(bind=engine)
  27.  
  28.  
  29.  
  30. app = FastAPI()
  31.  
  32. origins = [
  33.     "http://localhost:3001",
  34.     "http://localhost:3000",
  35.  
  36. ]
  37.  
  38. SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
  39. ALGORITHM = "HS256"
  40. ACCESS_TOKEN_EXPIRE_MINUTES = 30
  41.  
  42.  
  43.  
  44. app.add_middleware(
  45.     CORSMiddleware,
  46.     allow_origins=origins,
  47.     allow_credentials=True,
  48.     #allow_origin_regex = ["https://.*\.example\.org"],
  49.     allow_methods=["*"],
  50.     allow_headers=["*"],
  51.     expose_headers = []
  52. )
  53.  
  54. def get_db():
  55.     db = SessionLocal()
  56.     try:
  57.         yield db
  58.     finally:
  59.         db.close()
  60.  
  61.  
  62. BOOKS = [
  63.     {
  64.        
  65.         'title': 'On the Road',
  66.         'author': 'Jack Kerouac',
  67.        
  68.     },
  69.     {
  70.        
  71.         'title': 'Harry Potter and the Philosopher\'s Stone',
  72.         'author': 'J. K. Rowling',
  73.        
  74.     },
  75.     {
  76.        
  77.         'title': 'Green Eggs and Ham',
  78.         'author': 'Dr. Seuss',
  79.        
  80.     }
  81. ]
  82.  
  83. @app.get("/")
  84. async def root():
  85.     return {"message": "Hello World"}
  86.  
  87.  
  88. @app.get("/books")
  89. async def rat():
  90.     return BOOKS
  91.  
  92. #auth
  93. @app.post("/token", response_model=schemas.Token)
  94. async def login_for_access_token(username: str = Form(...), password: str = Form(...),  db: Session = Depends(get_db)):
  95.     print({username})
  96.     print({ password})
  97.  
  98.     user = crud.authenticate_user(db, username, password)
  99.    
  100.    
  101.     if not user:
  102.         raise HTTPException(
  103.             status_code=status.HTTP_401_UNAUTHORIZED,
  104.             detail="Incorrect username or password",
  105.             headers={"WWW-Authenticate": "Bearer"},
  106.         )
  107.     access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  108.     access_token = crud.create_access_token(
  109.         data={"sub": user.email}, expires_delta=access_token_expires
  110.     )
  111.     return {"access_token": access_token, "token_type": "bearer"}
  112.  
  113.  
  114. @app.get("/users/me/", response_model=schemas.Token)
  115. async def read_users_me(current_user: models.User = Depends(crud.get_current_active_user)):
  116.     return current_user
  117.  
  118.  
  119. @app.get("/users/me/items/")
  120. async def read_own_items(current_user: models.User = Depends(crud.get_current_active_user)):
  121.     return [{"item_id": "Foo", "owner": current_user.email}]
  122.  
  123. #endauth
  124.  
  125. @app.post("/users/", response_model=schemas.User)
  126. async def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
  127.     db_user = crud.get_user_by_email(db, email=user.email)
  128.     if db_user:
  129.         raise HTTPException(status_code=400, detail="Email already registered")
  130.     return crud.create_user(db=db, user=user)
  131.  
  132.  
  133. @app.get("/users/", response_model=List[schemas.User])
  134. async def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
  135.     users = crud.get_users(db, skip=skip, limit=limit)
  136.     return users
  137.  
  138.  
  139. @app.get("/users/{user_id}", response_model=schemas.User)
  140. async def read_user(user_id: int, db: Session = Depends(get_db)):
  141.     db_user = crud.get_user(db, user_id=user_id)
  142.     if db_user is None:
  143.         raise HTTPException(status_code=404, detail="User not found")
  144.     return db_user
  145.  
  146. @app.delete("/users/{user_id}",  response_model=schemas.UserDelete)
  147. async def delete_user(user_id: int, db: Session = Depends(get_db)):
  148.     db_user = crud.delete_user(db, user_id=user_id)
  149.    
  150.     return db_user
  151.  
  152. @app.put("/users/{user_id}", response_model=schemas.User)
  153. async def put_user(user_id: int, user: schemas.UserUpdate, db: Session = Depends(get_db)):
  154.     return  crud.update_user(db=db, user_id=user_id, user=user )
  155.  
  156. @app.post("/users/{user_id}/items/", response_model=schemas.Item)
  157. async def create_item_for_user(
  158.     user_id: int, item: schemas.ItemCreate, db: Session = Depends(get_db)
  159. ):
  160.     return crud.create_user_item(db=db, item=item, user_id=user_id)
  161.  
  162.  
  163. @app.get("/items/", response_model=List[schemas.Item])
  164. async def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
  165.     items = crud.get_items(db, skip=skip, limit=limit)
  166.     return items
  167.  
  168.  
RAW Paste Data