async def items_list_cost( request: InsuranceListCostRequest, profile: Profile = Depends(profile_manager.with_profile), trader_manager: TraderManager = Depends( Provide[AppContainer.trader.manager]), ) -> Union[TarkovSuccessResponse[Dict[str, dict]], TarkovErrorResponse]: insurance_data: Dict[str, dict] = {} for trader_id in request.traders: trader = trader_manager.get_trader(TraderType(trader_id)) trader_view = trader.view(player_profile=profile) trader_items: Dict[TemplateId, int] = {} for item_id in request.items: item = profile.inventory.get(item_id) trader_items[item.tpl] = trader_view.insurance_price([item]) insurance_data[trader_id] = trader_items return TarkovSuccessResponse(data=insurance_data)
def login_access_token( db_session: Session = Depends(get_db), form_data: OAuth2PasswordRequestForm = Depends(), ): """ NOTE: Using the dependency class `OAuth2PasswordRequestForm` creates the following Form request parameters for the endpoint: - grant_type: the OAuth2 spec says it is required and MUST be the fixed string "password". Nevertheless, this dependency class is permissive and allows not passing it. If you want to enforce it, use instead the OAuth2PasswordRequestFormStrict dependency. - username: username string. The OAuth2 spec requires the exact field name "username". - password: password string. The OAuth2 spec requires the exact field name "password". - scope: Optional string. Several scopes (each one a string) separated by spaces. E.g. "items:read items:write users:read profile openid" - client_id: optional string. OAuth2 recommends sending the client_id and client_secret (if any) using HTTP Basic auth, as: client_id:client_secret - client_secret: optional string. OAuth2 recommends sending the client_id and client_secret (if any) using HTTP Basic auth, as: client_id:client_secret """ user = crud.user.authenticate(db_session, user_email=form_data.username) if not user: raise HTTPException(status_code=400, detail="Incorrect email or password") access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) return { "access_token": create_access_token(payload={"user_id": user.id}, expires_delta=access_token_expires), "token_type": "bearer", }
async def delete_migration(migration_id: str, repos: RepoProvider = Depends(repos_provider)): """ Remove the migration model from Db :param migration_id: Migration Id :param repos: RepoProvider :return: Result message """ repo = repos.migration_repo await repo.delete_async(migration_id) return "Migration was deleted successfully"
async def create_migration(bind: MigrationBind, repos: RepoProvider = Depends(repos_provider)): """ Creates the migration model by provided configuration :param bind: Migration configuration :param repos: RepoProvider :return: Migration model """ migration_repo = repos.migration_repo created_migration = await migration_repo.create_async(bind) return created_migration
async def get_migration_state(migration_id, repos: RepoProvider = Depends(repos_provider)): """ Returns the migration state by Id :param repos: RepoProvider :param migration_id: Migration Id :return: MigrationState """ repo = repos.migration_repo migration = await repo.get_async(migration_id) return migration.migration_state
async def get_user_assort_price( trader_id: str, profile: Profile = Depends(profile_manager.with_profile_readonly), trader_manager: TraderManager = Depends(Provide[AppContainer.trader.manager]), ) -> Union[TarkovSuccessResponse[Dict[ItemId, List[List[dict]]]], TarkovErrorResponse]: trader = trader_manager.get_trader(TraderType(trader_id)) items = {} for item in profile.inventory.items.values(): if item.parent_id != profile.inventory.root_id: continue if not trader.can_sell(item): continue children_items = profile.inventory.iter_item_children_recursively(item) price = trader.get_sell_price(item, children_items=children_items) items[item.id] = [[{"_tpl": price.template_id, "count": price.amount}]] # TODO: Calculate price for items to sell in specified trader # output is { "item._id": [[{ "_tpl": "", "count": 0 }]] } return TarkovSuccessResponse(data=items)
async def register_user( register_request: RegisterRequest, db: Session = Depends(get_db) ): """Register a new user. The user will have to verify their account via /auth/verify.""" db_user = crud.get_user_by_username(db, username=register_request.username) if db_user: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="A user with this username is already registered", ) return crud.create_user(db=db, user=register_request)
def match_user(body: MatchBody, user: User = Depends(get_current_user)): if body.type == 'artist': user_taste = Taste.from_orm(user.taste) genres_dict = user_taste.taste.genres recomend = False for genre in body.genres: if genre in genres_dict: if genres_dict[genre] > 5: recomend = True break return {'recomend': recomend, 'id': body.id}
async def register_asset(topio_asset: TopioAssetCreate, db: Session = Depends(get_db)): topio_asset_orm = TopioAssetORM( local_id=topio_asset.local_id, owner_id=topio_asset.owner_id, asset_type=topio_asset.asset_type, description=topio_asset.description) db.add(topio_asset_orm) db.commit() db.refresh(topio_asset_orm) return topio_asset_orm
async def post_message( body: dict = Body( ..., example={ "message": "Post your message here, it will be relayed to twitch chat" }), api_key: APIKey = Depends(get_api_key), ): """Manual testing curl --header "Content-Type: application/json" --header "access_token: testKey" --request POST --data '{"message":"Test message sent from a json post"}' http://localhost:5000/post_message curl --header "Content-Type: application/json" --request POST --data '{"message":"Test"}' http://localhost:5000/post_message?access_token=testKey """ # noqa E501 if body.get("message", False): uri = "ws://bot:13337" try: async with websockets.connect(uri) as s: # We don't actually need this, but we have to read it before the bot will accept commands await s.recv() # There are two entries returned, and we need to retrieve both await s.recv() msg = dict( type="send_privmsg", channel=getenv("TWITCH_CHANNEL"), message=f"🤖 {body['message']}", ) msg_txt = json.dumps(msg) + "\n" await s.send(msg_txt.encode("utf8")) await s.send("\n".encode("utf8")) # Check if the message was successful resp = json.loads(await s.recv()) print(resp) if resp.get("type", "fail") != "success": return JSONResponse({ "success": False, "detail": "Error sending bot message." }) return JSONResponse({"success": True}) except ConnectionRefusedError: print("Unable to connect to bot.") return JSONResponse({ "success": False, "detail": "Unable to connect to bot." }) except Exception as e: print(f"Unknown exception trying to send message to bot. {e}") return JSONResponse({"success": False, "detail": str(e)})
async def put_contract_file_upload( item_id: int, cpf: Optional[UploadFile] = File([]), proof_of_income: Optional[UploadFile] = File([]), property_images: Optional[List[UploadFile]] = File([]), db: Session = Depends(get_db), ): """ Atualiza os arquivos enviados para um contrato por id """ # contrato nao existe contract: Contract = db.query(Contract).get(item_id) if contract is None: raise HTTPException(HTTPStatus.NOT_FOUND) # atualizacao dos arquivos somente em alguns status if contract.status not in [ ContractStatus.CREATED, ContractStatus.IMAGES_UPLOADED ]: raise HTTPException(HTTPStatus.BAD_REQUEST) ###### # A maioria deste codigo estaria melhor posicionado em uma camada de servicos que tratasse o upload # para a cloud e atualizasse o contrato. Isto evitaria bastante duplicacao de codigo aqui. # # logica de negocios em views eh uma pessima pratica, mas isto eh soh um exemplo ###### # aqui se faria o upload para algum storage como um AWS S3, etc... por simplicidade, vou apenas gerar uma URL # falsa que sera salva no banco de dados como se tivesse retornado do storage. if cpf: contract.cpf_url = f"http://dummy/{cpf.filename}" if proof_of_income: contract.proof_of_income_url = f"http://dummy/{proof_of_income.filename}" db.add(contract) # aqui optei por substituir as imagens anteriores, mas elas poderiam ser mantidas e mais endpoints # poderiam ser criados para um gerenciamento mais detelhado. if property_images: contract.property_images = [] db.flush() for i in property_images: if i.filename: file_url = f"http://dummy/{i.filename}" image = PropertyImage(contract_id=contract.id, url=file_url) db.add(image) db.commit() db.refresh(contract) return contract
def create_course(*, session: Session = Depends(get_session), course: CourseCreate, current_user: User = Depends(deps.get_current_user)): db_course = Course.from_orm(course, {"user_id": current_user.id}) session.add(db_course) session.commit() session.refresh(db_course) new_assignments = [] for assignment in course.assignments: new_assignment = Assignment.from_orm(assignment, {"course_id": db_course.id}) new_assignments.append(new_assignment) session.add_all(new_assignments) db_course.assignments = new_assignments session.commit() session.refresh(db_course) return db_course
async def post_contract(new_contract: ContractCreateSchema, db: Session = Depends(get_db)): """ Cria um novo contrato """ try: contract = Contract(**new_contract.dict()) db.add(contract) db.commit() except IntegrityError: # algum index unique ja existe, como email raise HTTPException(409) return contract
def login( email: str = Body(..., embed=True), password: str = Body(..., embed=True), account_service: AccountService = Depends( Provide[AppContainer.launcher.account_service]), ) -> PlainTextResponse: try: account_service.find(email=email, password=password) return PlainTextResponse(content=zlib.compress("OK".encode("utf8"))) except NotFoundError: return PlainTextResponse( content=zlib.compress("FAILED".encode("utf8")))
async def create_course(course: CourseIn, university_code: str, account: Account = Depends(auth_account)): data = dict(course.dict(), universityID=await get_university_id(university_code)) dep, num = parse_course_code(data['code']) data['departmentCode'] = dep data['code'] = dep + num await db.execute( 'INSERT INTO Course ({}) VALUES ({})'.format( ', '.join(data), ', '.join(':' + i for i in data)), data) return Course(**data)
def delete_project_id(id: int, db: Session = Depends(database.get_db)): selected_project = db.query( models.Project).filter(models.Project.id == id).first() if not selected_project: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Project {id} not found.") db.delete(selected_project) db.commit() return {'status': f'delete project_id {id} successful'}
def create_profile( profile_id: str = Cookie(..., alias="PHPSESSID"), side: str = Body(..., embed=True), nickname: str = Body(..., embed=True), profile_service: ProfileService = Depends(Provide[AppContainer.profile.service]), ) -> TarkovSuccessResponse[dict]: profile = profile_service.create_profile( profile_id=profile_id, nickname=nickname, side=side, ) return TarkovSuccessResponse(data={"uid": profile.id})
async def create_product(product: ProductIn, session: Session = Depends(get_session)): product_in_db = ProductInDB(**product.dict()) # Create session.add(product_in_db) session.commit() session.refresh(product_in_db) product_out = ProductOut(**product_in_db.__dict__) return product_out
def nickname_validate( nickname: str = Body(..., embed=True), account_service: AccountService = Depends( Provide[AppContainer.launcher.account_service]), ) -> Union[TarkovSuccessResponse, TarkovErrorResponse]: if len(nickname) < 3: return TarkovErrorResponse(errmsg="Nickname is too short", err=256) if account_service.is_nickname_taken(nickname): return TarkovErrorResponse(errmsg="Nickname is taken", err=255) return TarkovSuccessResponse(data={"status": "ok"})
def login_access_token( session: Session = Depends(get_session), form_data: OAuth2PasswordRequestForm = Depends(), ) -> Any: """ OAuth2 compatible token login, get an access token for future requests """ user = authenticate_user(session, email=form_data.username, password=form_data.password) if not user: raise HTTPException(status_code=400, detail="Incorrect email or password") elif not user.is_active: raise HTTPException(status_code=400, detail="Inactive user") token = security.create_access_token( user.id, expires_delta=timedelta(minutes=security.ACCESS_TOKEN_EXPIRE_MINUTES)) return { "access_token": token, "token_type": "bearer", }
def update_project_id(id: int, request: schema.Project, db: Session = Depends(database.get_db)): #Search for projects' id selected_project = db.query(models.Project).filter(models.Project.id == id) if not selected_project.first(): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"Project {id} not found.") selected_project.update(dict(request)) return {'status': f'project {id} updated'}
async def health_sync( request: Request, profile: Profile = Depends(with_profile), ) -> TarkovSuccessResponse: body = await request.json() profile.pmc.Health["Hydration"]["Current"] = body["Hydration"] profile.pmc.Health["Energy"]["Current"] = body["Energy"] for limb, health in body["Health"].items(): profile.pmc.Health["BodyParts"][limb]["Health"] = health return TarkovSuccessResponse(data=None)
def update(model_py: klass_py, sess: Session = Depends(create_session)): if model_py.id is None: raise HTTPException(400, f"{name} id is not given") model_orm: klass_orm = sess.query(klass_orm).filter( klass_orm.id == model_py.id).one() for f, v in model_py.dict(exclude_none=True, exclude_unset=True).items(): if type(v) is dict: # nested models are usually mapped to foreign key objects continue setattr(model_orm, f, v) sess.add(model_orm) return
async def match_user(id: str, current_user: User = Depends(get_current_user), db: Session = Depends(get_db)): db_user = get_user(db, id) if not db_user: return {"message": "Sorry this user not in out database", "match": 0} if db_user.id == current_user.id: return { "message": "You have perfect match with yourself", "match": 100 } if not db_user.taste: return { "message": "Your friend should update spotify data to app", "match": 0 } if not current_user.taste: return {"message": "Please update your spotify data", "match": 0} db_user_tastes = Taste.from_orm(db_user.taste).taste current_user_tastes = Taste.from_orm(current_user.taste).taste matcher = MatchUsers(current_user_tastes, db_user_tastes) features_match = matcher.match_features() artists_match = matcher.match_artists() genres_match = matcher.match_genres() total_match = pd.Series( [features_match, artists_match[1], genres_match[1]]).mean() return { "features_match": features_match, "artists_match": artists_match, "genres_match": genres_match, "match": total_match }
async def update_course(course: CourseUpdateIn, university_code: str, course_code: str, account: Account = Depends(auth_account)): fields = course.__fields__ data = dict(course.dict(), universityID=await get_university_id(university_code), code=course_code) await ensure_course_exists(data['code'], data['universityID']) await db.execute( 'UPDATE Course SET {} WHERE code = :code AND universityID = :universityID' .format(', '.join('{0} = :{0}'.format(i) for i in fields)), data) return Course(**data)
def update_topping( tid: int, topping: schemas.ToppingRequestUpdate, dbb: Session = Depends(get_db), ): prev_top = get_topping_by_id_if_exists(tid, dbb) topping_update = schemas.ToppingUpdate( topping_id=tid, name=topping.name if topping.name else prev_top.name, price=topping.price if topping.price else prev_top.price, ) return Crud.update_topping(dbb, topping_update)
async def updateUser(user: User, db: Session = Depends(db.get_db)): selectUserById = db.query(DB_User).filter(DB_User.id == user.id).first() if selectUserById is None: raise HTTPException(status_code=404, detail="Don't exist user!!") selectUserById.username = user.username selectUserById.password = user.password selectUserById.email = user.email selectUserById.sex = user.sex db.commit() db.refresh(selectUserById) return selectUserById
def get_current_user(db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)): credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = jwt.decode(token, settings.JWT_SECRET_KEY, algorithms=[settings.JWT_ALGORITHM]) email: str = payload.get("sub") print(email) if email is None: raise credentials_exception token_data = TokenData(email=email) except JWTError: raise credentials_exception user = get_user_by_email(db=db, email=email) if user is None: raise credentials_exception return user
def imagepath_parameter(filepath: str = PathParam( ..., description="The file path, relative to server base path.", example='123/my-file.ext'), config: Settings = Depends(get_settings)): path = filepath2path(filepath, config) if not path.exists(): from pims.api.exceptions import FilepathNotFoundProblem raise FilepathNotFoundProblem(path) if not path.is_single(): from pims.api.exceptions import NoAppropriateRepresentationProblem raise NoAppropriateRepresentationProblem(path) return path
def update_drink( did: int, drink: schemas.DrinkRequestUpdate, dbb: Session = Depends(get_db), ): prev_drink = get_drink_by_id_if_exists(did, dbb) drink_update = schemas.DrinkUpdate( drink_id=did, name=drink.name if drink.name else prev_drink.name, price=drink.price if drink.price else prev_drink.price, ) return Crud.update_drink(dbb, drink_update)