def use_coupon(invoice: Invoice, response: Response, user_id=Depends(JWTBearer())): d = invoice.json() create_invoice.delay(invoice.json(), 5) return '{complete!}'
def add_order(order: Order, user_id=Depends(JWTBearer())): # use delay() method to call the celery task create_order.delay(order.customer_name, order.order_quantity) return {"message": "Order Received! Thank you for your patience."}
import requests import json from app.utils.config_files import ConfigFiles from app.model.response import getResponse from app.model.clienteModel import ClienteModel from app.data.clienteData import ClienteFactory from app.service.clienteServices import InserirCliente, BuscarPorId, DeletaPorId, AtualizarCliente, BuscarTodos from app.auth.auth_bearer import JWTBearer from app.auth.auth_handler import signJWT router_cliente = APIRouter( prefix="/Cliente", tags=["Cliente"] ) @router_cliente.post("/Adicionar/", dependencies=[Depends(JWTBearer())]) async def addCliente(ClienteModel: ClienteModel): response = InserirCliente(ClienteModel) return JSONResponse(status_code = response.status, content = response.__dict__) @router_cliente.get("/BuscarPorId/{id}", dependencies=[Depends(JWTBearer())]) async def buscarId(id: int): response = BuscarPorId(id) return JSONResponse(status_code = response.status, content = response.__dict__) @router_cliente.delete("/Deletar/{id}", dependencies=[Depends(JWTBearer())]) async def deletarCliente(id: int): response = DeletaPorId(id) return JSONResponse(status_code = response.status,
def create_coupon(coupon: Coupon, response: Response, user_id=Depends(JWTBearer())): #user_id=Depends(JWTBearer()) ps_connection = get_connection() cur = ps_connection.cursor() try: coupon_ = get_coupon(coupon.coupon_code) if coupon_ is not None: response.status_code = status.HTTP_409_CONFLICT return "Coupon_code already exists!" # raise HTTPException(status_code=409, detail="Coupon_code already exists!") results = ''' { "results": { "discount_type": ''' + str(coupon.discount_type) + ''', "discount_percent": ''' + str(coupon.discount_percent) + ''', "discount_ceil": ''' + str(coupon.discount_ceil) + ''', "discount_amount": ''' + str(coupon.discount_amount) + ''' } } ''' rule = ''' { "rule": { "user_id": ''' + str(coupon.user_id) + ''', "product_id": ''' + str(coupon.product_id) + ''', "expire_date": "''' + str(coupon.expire_date) + '''", "count_of_use": ''' + str(coupon.count_of_use) + ''' } } ''' create_date = datetime.datetime.now( pytz.timezone('Asia/Tehran')).strftime("%Y-%m-%d %H:%M:%S") # date.today() segment = """ INSERT INTO coupons (coupon_code , created_at ,results , rule ,description , user_id ) values (%s,%s,%s,%s,%s,%s) RETURNING id""" record_to_insert = (coupon.coupon_code, str(create_date), results, rule, coupon.description, int(coupon.user_id)) cur.execute(segment, record_to_insert) ps_connection.commit() count = cur.rowcount coupon_id = cur.fetchone()[0] print(count, "Record inserted successfully into coupons table") print( datetime.datetime.now( pytz.timezone('Asia/Tehran')).strftime("%Y-%m-%d %H:%M:%S")) # data = ''' # { # "id": ''' + str(coupon_id) + ''', # "coupon_code": ''' + str(coupon.coupon_code) + ''', # "created_at": "''' + str(create_date) + '''", # "results": [''' + str(results) + '''], # "rule": [''' + str(rule) + '''], # "description": "''' + str(coupon.description) + '''", # "user_id": ''' + str(coupon.user_id) + ''' # } # ''' data = CouponOut(id=coupon_id, user_id=coupon.user_id, coupon_code=coupon.coupon_code, created_at=create_date, rule=rule, results=results, description=coupon.description) # status_ = set_routes_to_cache(key="coupon-code:"+str(coupon.coupon_code), value=data.json()) # if not status_: # response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR # return "Failed to set redis key" # print(get_routes_from_cache(key="coupon-code:"+str(coupon.coupon_code))) response.status_code = status.HTTP_201_CREATED except (Exception, psycopg2.Error) as error: raise HTTPException(status_code=500, detail="Internal server error!") # response.status_code = status.HTTP_500_INTERNAL_SERVER_ERROR # if ps_connection: # print("Failed to insert record into coupons table", error) return data
@app.get("/posts", tags=["posts"]) async def get_posts() -> dict: return {"data": posts} @app.get("/posts/{id}", tags=["posts"]) async def get_single_post(id: int) -> dict: if id > len(posts): return {"error": "No such post with the supplied ID."} for post in posts: if post["id"] == id: return {"data": post} @app.post("/posts", dependencies=[Depends(JWTBearer())], tags=["posts"]) async def add_post(post: PostSchema) -> dict: post.id = len(posts) + 1 posts.append(post.dict()) return {"data": "post added."} @app.post("/user/signup", tags=["user"]) async def create_user(user: UserSchema = Body(...)): #user.password=CryptContext(schemes=["bcrypt"], deprecated="auto") users.append( user) # replace with db call, making sure to hash the password first return signJWT(user.email) def check_user(data: UserLoginSchema):
from app.auth.auth_bearer import JWTBearer from app.auth.auth_handler import signJWT travels_router = APIRouter() travels = [{"id": 1, "title": "t1", "content": "Lorem Ipsum ..."}] @travels_router.get("/", tags=["travels"]) async def get_travels() -> dict: return {"data": travels} @travels_router.get("/{id}", tags=["travels"]) async def get_single_travel(id: int) -> dict: if id > len(travels): return {"error": "No such post with the supplied ID."} for t in travels: if t["id"] == id: return {"data": t} @travels_router.post("/", dependencies=[Depends(JWTBearer())], tags=["travels"]) async def add_travel(add_travel: TravelsSchema) -> dict: add_travel.id = len(travels) + 1 travels.append(add_travel.dict()) return {"data": "post added."}
else: if show: results = [id for id in search_util.search(query, int(show))] else: results = [id for id in search_util.search(query)] if len(results) > 0: resultsData = DocumentFacade.getAllDetailsIn(results) except Exception as error: logger.error(error) raise HTTPException(status_code=500, detail="Search failed") return resultsData @app.get('/update_index/', response_model=Count, dependencies=[Depends(JWTBearer(applications=[UPDATE_AUTH_ROLE]))]) async def re_index() -> Count: try: Documents = DocumentFacade.getAll() DocumentIds, titles = zip( *[Document.values() for Document in Documents]) asyncio.get_event_loop().create_task( search_util.index_items(DocumentIds, titles)) except Exception as e: raise HTTPException(status_code=500, detail="Updating failed" + str(e)) return {'count': len(DocumentIds)} class IndexStatus(BaseModel): DocumentsCount: int indexCount: int
def check_user(data: UserLoginSchema): id = get_UserAuth(data.email) if id != None: return (getEncodedPassword( data.password, get_UserHashedSalt(id)) == get_UserHashedPass(id)) return False @app.post("/user/login", tags=["user"]) async def user_login(user: UserLoginSchema = Body(...)): if check_user(user): return signJWT(user.email) raise HTTPException(status_code=401, detail="Wrong Login Details") @app.get("/user/profile", dependencies=[Depends(JWTBearer())], tags=["posts"]) async def alumno(Authorization: Optional[List[str]] = Header(None)) -> dict: token = Authorization[0].replace("Bearer ", "") email = decodeJWT(token)['user_id'] if "@upm.es" in email: profesorList = get_Professor(email)[0] return { "name": profesorList[0], "email": profesorList[1], "departamento": profesorList[2] } else: alumno = get_Alumno(email, bbdd="isst") return { "name": alumno[1].split(" ")[0], "surname": alumno[1].split(" ")[1],
async def login_user(user: UserLoginSchema = Body(...)): cur.execute(f"SELECT * FROM users WHERE email='{user.email}';") data = cur.fetchall() if data: hashed = data[0][2] # hashed password from database if pwd_context.verify(user.password, hashed): user_id = data[0][0] user_role = data[0][3] return {"token": signJWT(user_id, user_role)} else: return {"error": f"Wrong password for {user.email}!"} else: return {"error": "Wrong email!"} @app.get("/logout", dependencies=[Depends(JWTBearer())], tags=["users"]) async def logout_user(): return {"message": "logged out!"} @app.post("/book/add", dependencies=[Depends(LibrarianBearer())], tags=["books"]) async def add_book(book: BookSchema): cur.execute(f"SELECT title FROM book WHERE title='{book.title}';") if cur.fetchall(): # if there is already a book with that title return {"error": "Book already exists at the library!"} else: cur.execute(f'''INSERT INTO book (title, author, des) VALUES('{book.title}','{book.author}', '{book.des}');''') con.commit() body = {"title": f'"{book.title}"'} es.index(index='library', doc_type='book', body=body)