def _get_json_response(data: Any, extra_headers: Dict[str, str] = None) -> JSONResponse: try: if extra_headers: return JSONResponse(data, headers=extra_headers) else: return JSONResponse(data) except (TypeError, ValueError): err_msg = "Error trying to serialize response data to JSON" logger.exception(err_msg) raise HTTPException(status_code=500, detail=err_msg)
async def verify( self, token: str, ) -> str: response = await self.client.post(self.verify_url, json={"token": token}) try: response.raise_for_status() except HTTPError: raise HTTPException(status_code=response.status_code, detail="Not authenticated") finally: data = response.json() token = data.get("token", None) if token is None: raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Not authenticated") return token
async def groups_stats( db: AsyncIOMotorClient = Depends(get_database) ): stats = await get_groups_stats(db) if not stats: raise HTTPException( status_code=HTTP_404_NOT_FOUND, detail=f"Stats not found", ) return stats
async def post(self, *args, **kwargs) -> Response: json_body = await self.deserialize_body() user = User() username = json_body.get('username') if username: user.username = username else: raise HTTPException(status_code=400, detail='A valid `username` is required.') organization_id = json_body.get('organization') try: org = await Organization.get(id=int(organization_id)) user.organization = org except (DoesNotExist, ValueError, TypeError): raise HTTPException(status_code=404, detail='Related Organization not found.') await user.save() result = await self.serialize(data=user) return await self.to_response(result, status_code=201)
async def remove_roi_contour(camera_id: str, reboot_processor: Optional[bool] = True): """ Delete the defined RoI for a camera. """ validate_camera_existence(camera_id) roi_file_path = ObjectsFilteringPostProcessor.get_roi_file_path(camera_id, settings.config) if not validate_file_exists_and_is_not_empty(roi_file_path): detail = f"There is no defined RoI for {camera_id}" raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=detail) os.remove(roi_file_path) success = restart_processor() if reboot_processor else True return handle_response(None, success, status.HTTP_204_NO_CONTENT)
async def app(request: Request) -> Response: try: body = None if body_field: if is_body_form: body = await request.form() else: body_bytes = await request.body() if body_bytes: body = await request.json() except Exception as e: logger.error(f"Error getting request body: {e}") raise HTTPException( status_code=400, detail="There was an error parsing the body" ) from e solved_result = await solve_dependencies( request=request, dependant=dependant, body=body, dependency_overrides_provider=dependency_overrides_provider, ) values, errors, background_tasks, sub_response, _ = solved_result if errors: raise RequestValidationError(errors, body=body) else: raw_response = await run_endpoint_function( dependant=dependant, values=values, is_coroutine=is_coroutine ) if isinstance(raw_response, Response): if raw_response.background is None: raw_response.background = background_tasks return raw_response response_data = await serialize_response( field=response_field, response_content=raw_response, include=response_model_include, exclude=response_model_exclude, by_alias=response_model_by_alias, exclude_unset=response_model_exclude_unset, exclude_defaults=response_model_exclude_defaults, exclude_none=response_model_exclude_none, is_coroutine=is_coroutine, ) response = response_class( content=response_data, status_code=status_code, background=background_tasks, ) response.headers.raw.extend(sub_response.headers.raw) if sub_response.status_code: response.status_code = sub_response.status_code return response
async def get(self, request: Request): """ Handle a GET request. thing_id -- ID of the thing this request is for """ thing_id = request.path_params.get("thing_id", "0") thing = await self.get_thing(thing_id) if thing is None: raise HTTPException(status_code=404) return UJSONResponse(await thing.get_event_descriptions())
async def __call__(self, request: Request) -> Optional[dict]: token = self.getter(request).get(self.model.name) if not token: if self.auto_error: raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Not authenticated") else: return None verified_token = await self.verify(token) return self.decode(verified_token)
async def get_wikidata(wikidata_id): wikidata_id = wikidata_id.upper() if not re.match(r"^Q[0-9]+$", wikidata_id): return None async with aiohttp.ClientSession() as session: async with session.get( f"https://www.wikidata.org/entity/{wikidata_id}.json") as resp: if resp.status != 200: raise HTTPException(503, "Error while fetching wikidata") data = await resp.json() return data["entities"][wikidata_id]
async def handle(self, scope: Scope, receive: Receive, send: Send) -> None: if self.methods and scope["method"] not in self.methods: headers = {"Allow": ", ".join(self.methods)} if "app" in scope: raise HTTPException(status_code=405, headers=headers) else: response = PlainTextResponse("Method Not Allowed", status_code=405, headers=headers) await response(scope, receive, send) else: await self.app(scope, receive, send)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()) -> Token: user = await authenticate_user(form_data.username, form_data.password) if not user: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect username or password", ) access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) access_token = create_access_token( data={"sub": user.username}, expires_delta=access_token_expires ) return Token(access_token=access_token, token_type='bearer')
def necropolis_items(query): """Return records from a necropolis search query Arguments: - query: instance of NecropolisQuery, which has a `query' property. """ try: resp = requests.post("%s/_search" % dplaapi.NECRO_BASE, json=query.query) resp.raise_for_status() except requests.exceptions.HTTPError: if resp.status_code == 400: # Assume that a Bad Request is the user's fault and we're getting # this because the query doesn't parse due to a bad search term # parameter. For example "this AND AND that". raise HTTPException(400, 'Invalid query') else: log.exception('Error querying Elasticsearch') raise HTTPException(503, 'Backend search operation failed') result = resp.json() return result
async def get_question(request: Request) -> UJSONResponse: question_id = request.path_params["question_id"] question = await Question.filter(id=question_id).first().values() try: question = QuestionResponse(**question[0]).as_dict() except IndexError: # there is no question with such id raise HTTPException( status_code=404, detail=f"There is no question with id {question_id}") return UJSONResponse(question)
async def confirm_registration(request: Request): if 'confirmation_id' not in request.query_params: raise HTTPException(400) confirmation_id = request.query_params['confirmation_id'] query = ( select(model.User) .where( model.User.confirmation_id == confirmation_id ) ) result = await request.connection.execute(query) user = result.scalars().first() if not user: raise HTTPException(404) user.confirmed = True return Response(content='OK')
def validate_all_scopes(request: Request, scopes: SecurityScopes): """Validate that all defined scopes exist in 'request.auth.scopes'. Usage: >>> from fastapi import Security >>> @app.get("/my_name", dependencies=[ ... Security(validate_all_scopes, scopes=["read", "write"]) ... ]) """ req_scopes = request.auth.scopes if not all(scope in req_scopes for scope in scopes.scopes): raise HTTPException(status.HTTP_403_FORBIDDEN)
async def get(self, request: Request) -> StreamingResponse: """Get single video as streamed response""" filename = request.path_params["filename"] path_to_video = settings.VIDEOS_PATH / filename if not path_to_video: raise HTTPException(status_code=404) async def video_generator(path_to_file: str, blocksize: int = 1024 * 256): async with aiofiles.open(path_to_file, mode="rb") as file: while chunk := await file.read(blocksize): yield chunk
def test_starlette_error(self): request = mock.Mock() exc = HTTPException(404, "something bad") response = starlette.exception_handler(request, exc) assert response.status_code == 404 assert json.loads(response.body) == { "message": "something bad", "debug_message": "(404, 'something bad')", "code": None, }
async def get_commons_thumbnail(filename, width=300): url = ( "https://commons.wikimedia.org/w/api.php?" f"action=query&titles=Image:{filename}&prop=imageinfo" f"&iiprop=url&iiurlwidth={width}&format=json" ) async with aiohttp.ClientSession() as session: async with session.get(url) as resp: if resp.status != 200: raise HTTPException(503, "Error while fetching wikimedia commons image") data = await resp.json() return list(data["query"]["pages"].values())[0]
async def create_product_inventory( inventory: Inventory = Body(..., embed=True), db: AsyncIOMotorClient = Depends(get_database)): inventory_by_product = await get_inventory_for_product( db, inventory.product) if inventory_by_product: raise HTTPException( status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail= f"inventory already exists. name={inventory_by_product.product}") db_inventory = await create_inventory(db, inventory) return db_inventory
def route_search_users( q: str, skip: int = 0, limit: int = 100, current_user: UserInDB = Depends(get_current_user), ): """ Search users, use Bleve Query String syntax: http://blevesearch.com/docs/Query-String-Query/ For typeahead sufix with `*`. For example, a query with: `email:johnd*` will match users with email `[email protected]`, `[email protected]`, etc. """ if not check_if_user_is_active(current_user): raise HTTPException(status_code=400, detail="Inactive user") elif not check_if_user_is_superuser(current_user): raise HTTPException( status_code=400, detail="The user doesn't have enough privileges" ) bucket = get_default_bucket() users = search_users(bucket=bucket, query_string=q, skip=skip, limit=limit) return users
async def get(self, request: Request) -> Response: permalink = "/" + request.path_params["permalink"] for page in resources.index.pages: if page.permalink == permalink: break else: raise HTTPException(404) context = {"request": request, "page": page, **_common_context()} return resources.templates.TemplateResponse("views/page.jinja", context=context)
async def set_teams( game_id: str, teams: List[Player], player: User = Depends(get_current_user), ): if player.uid not in games[game_id].players: raise HTTPException(status_code=HTTP_400_BAD_REQUEST, detail=f"Player {player.uid} not in Game.") if not all([_p.uid in games[game_id].players for _p in teams]): # check validity of teams raise HTTPException(status_code=HTTP_400_BAD_REQUEST, detail=f"Players not in Game.") res = games[game_id].change_teams(teams) if res['requestValid']: await sio_emit_game_state(game_id) else: raise HTTPException(status_code=HTTP_400_BAD_REQUEST, detail=res["note"]) return return games[game_id].public_state()
def get_camera_index(config_dict: Dict, camera_id: str) -> int: """ Returns the section source index for the camera <camera_id> """ camera_names = [x for x in config_dict.keys() if x.startswith("Source_")] cameras = [map_camera(x, config_dict) for x in camera_names] cameras_ids = [camera["id"] for camera in cameras] try: index = cameras_ids.index(camera_id) except ValueError: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"The camera: {camera_id} does not exist") return index
async def accept_language(request: Request) -> Response: """Return plain password only for russian Accept-Language header.""" accept_language_header = request.headers.get("accept-language", "").lower() if "ru" not in accept_language_header: raise HTTPException( status_code=status.HTTP_406_NOT_ACCEPTABLE, detail="Я говорю только по русски, товарищ.", ) return PasswordResponse(passwords.REDIRECT, key="пароль")
async def remove_in_out_boundaries(camera_id: str, reboot_processor: Optional[bool] = True): """ Delete the defined In/Out boundaries for a camera. """ validate_camera_existence(camera_id) in_out_file_path = InOutMetric.get_in_out_file_path(camera_id, settings.config) if not validate_file_exists_and_is_not_empty(in_out_file_path): detail = f"There is no defined In/Out Boundary for {camera_id}" raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=detail) os.remove(in_out_file_path) success = restart_processor() if reboot_processor else True return handle_response(None, success, status.HTTP_204_NO_CONTENT)
def sync_wrapper(*args: typing.Any, **kwargs: typing.Any) -> Response: request = kwargs.get("request") if request is None: request = args[idx] assert isinstance(request, Request) if not has_required_scope(request, scopes_list): if redirect is not None: return RedirectResponse(url=request.url_for(redirect)) raise HTTPException(status_code=status_code) return func(*args, **kwargs)
async def group_schedule_update( db: AsyncIOMotorClient = Depends(get_database) ): updates = await get_all_schedule_updates(db) if not updates: raise HTTPException( status_code=HTTP_404_NOT_FOUND, detail=f"Schedule updates not found", ) return updates
def validate_authenticated(request: Request): """Validate that 'request.user' is authenticated. Usage: >>> from fastapi import Depends >>> @app.get("/my_name", dependencies=[ ... Depends(validate_authenticated) ... ]) """ user: SimpleUser = getattr(request, "user", None) if user is not None and not user.is_authenticated: raise HTTPException(status.HTTP_401_UNAUTHORIZED)
async def delete_user(email: str): # if email input is none, raise error if not email: raise HTTPException(status_code=400, detail="Input invalid/not present") # get DB Database db = get_database() # Delete User await utils.delete_user(email, db)
async def receiver(request: Request): try: json: dict = await request.json() except JSONDecodeError: raise HTTPException(403, "Access denied") if json.get("secret") != VK_SECRET_KEY: raise HTTPException(403, "Access denied") type_event = json.get("type") if type_event == "confirmation": return PlainTextResponse(VK_CONF_CODE) message: str = ujson.dumps(json) async with conns["channel_pool"].acquire() as channel: await channel.default_exchange.publish( aio_pika.Message(body=message.encode()), routing_key=RABBITMQ_QUEUE) return PlainTextResponse("ok")