Python fastapi.HTTPException() Examples
The following are 30
code examples of fastapi.HTTPException().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
fastapi
, or try the search function
.
Example #1
Source File: directions.py From idunn with Apache License 2.0 | 7 votes |
def get_directions_with_coordinates( # URL values f_lon: float, f_lat: float, t_lon: float, t_lat: float, # Query parameters type: str, language: str = "en", # Request request: Request = Depends(directions_request), ): from_place = Latlon(f_lat, f_lon) to_place = Latlon(t_lat, t_lon) if not type: raise HTTPException(status_code=400, detail='"type" query param is required') return directions_client.get_directions( from_place, to_place, type, language, params=request.query_params )
Example #2
Source File: closest.py From idunn with Apache License 2.0 | 6 votes |
def get_closest_place(lat: float, lon: float, es=None): if es is None: es = get_elasticsearch() es_addr = fetch_closest(lat, lon, es=es, max_distance=MAX_DISTANCE_IN_METERS) places = { "addr": Address, "street": Street, } loader = places.get(es_addr.get("_type")) if loader is None: logger.warning("Found a place with the wrong type") prometheus.exception("FoundPlaceWithWrongType") raise HTTPException( status_code=404, detail="Closest address to '{}:{}' has a wrong type: '{}'".format( lat, lon, es_addr.get("_type") ), ) return loader(es_addr["_source"])
Example #3
Source File: login.py From full-stack-fastapi-couchbase with MIT License | 6 votes |
def reset_password(token: str = Body(...), new_password: str = Body(...)): """ Reset password. """ username = verify_password_reset_token(token) if not username: raise HTTPException(status_code=400, detail="Invalid token") bucket = get_default_bucket() user = crud.user.get(bucket, username=username) if not user: raise HTTPException( status_code=404, detail="The user with this username does not exist in the system.", ) elif not crud.user.is_active(user): raise HTTPException(status_code=400, detail="Inactive user") user_in = UserUpdate(name=username, password=new_password) user = crud.user.update(bucket, username=username, user_in=user_in) return {"msg": "Password updated successfully"}
Example #4
Source File: login.py From full-stack-fastapi-couchbase with MIT License | 6 votes |
def login(form_data: OAuth2PasswordRequestForm = Depends()): """ OAuth2 compatible token login, get an access token for future requests. """ bucket = get_default_bucket() user = crud.user.authenticate( bucket, username=form_data.username, password=form_data.password ) if not user: raise HTTPException(status_code=400, detail="Incorrect email or password") elif not crud.user.is_active(user): raise HTTPException(status_code=400, detail="Inactive user") access_token_expires = timedelta(minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES) return { "access_token": create_access_token( data={"username": user.username}, expires_delta=access_token_expires ), "token_type": "bearer", }
Example #5
Source File: authentication.py From fastapi-realworld-example-app with MIT License | 6 votes |
def _get_current_user( users_repo: UsersRepository = Depends(get_repository(UsersRepository)), token: str = Depends(_get_authorization_header_retriever()), ) -> User: try: username = jwt.get_username_from_token(token, str(SECRET_KEY)) except ValueError: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail=strings.MALFORMED_PAYLOAD, ) try: return await users_repo.get_user_by_username(username=username) except EntityDoesNotExist: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail=strings.MALFORMED_PAYLOAD, )
Example #6
Source File: items.py From full-stack-fastapi-couchbase with MIT License | 6 votes |
def update_item( *, id: str, item_in: ItemUpdate, current_user: UserInDB = Depends(get_current_active_user), ): """ Update an item. """ bucket = get_default_bucket() doc = crud.item.get(bucket=bucket, id=id) if not doc: raise HTTPException(status_code=404, detail="Item not found") if not crud.user.is_superuser(current_user) and ( doc.owner_username != current_user.username ): raise HTTPException(status_code=400, detail="Not enough permissions") doc = crud.item.update( bucket=bucket, id=id, doc_in=item_in, owner_username=doc.owner_username ) return doc
Example #7
Source File: users.py From full-stack-fastapi-couchbase with MIT License | 6 votes |
def update_user( *, username: str, user_in: UserUpdate, current_user: UserInDB = Depends(get_current_active_superuser), ): """ Update a user. """ bucket = get_default_bucket() user = crud.user.get(bucket, username=username) if not user: raise HTTPException( status_code=404, detail="The user with this username does not exist in the system", ) user = crud.user.update(bucket, username=username, user_in=user_in) return user
Example #8
Source File: users.py From full-stack-fastapi-couchbase with MIT License | 6 votes |
def create_user( *, user_in: UserCreate, current_user: UserInDB = Depends(get_current_active_superuser), ): """ Create new user. """ bucket = get_default_bucket() user = crud.user.get(bucket, username=user_in.username) if user: raise HTTPException( status_code=400, detail="The user with this username already exists in the system.", ) user = crud.user.upsert(bucket, user_in=user_in, persist_to=1) if config.EMAILS_ENABLED and user_in.email: send_new_account_email( email_to=user_in.email, username=user_in.username, password=user_in.password ) return user
Example #9
Source File: login.py From full-stack-fastapi-couchbase with MIT License | 6 votes |
def recover_password(username: str): """ Password Recovery. """ bucket = get_default_bucket() user = crud.user.get(bucket, username=username) if not user: raise HTTPException( status_code=404, detail="The user with this username does not exist in the system.", ) password_reset_token = generate_password_reset_token(username=username) send_reset_password_email( email_to=user.email, username=username, token=password_reset_token ) return {"msg": "Password recovery email sent"}
Example #10
Source File: authentication.py From fastapi-realworld-example-app with MIT License | 6 votes |
def _get_authorization_header( api_key: str = Security(RWAPIKeyHeader(name=HEADER_KEY)), ) -> str: try: token_prefix, token = api_key.split(" ") except ValueError: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail=strings.WRONG_TOKEN_PREFIX, ) if token_prefix != JWT_TOKEN_PREFIX: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail=strings.WRONG_TOKEN_PREFIX, ) return token
Example #11
Source File: articles_common.py From fastapi-realworld-example-app with MIT License | 6 votes |
def mark_article_as_favorite( article: Article = Depends(get_article_by_slug_from_path), user: User = Depends(get_current_user_authorizer()), articles_repo: ArticlesRepository = Depends(get_repository(ArticlesRepository)), ) -> ArticleInResponse: if not article.favorited: await articles_repo.add_article_into_favorites(article=article, user=user) return ArticleInResponse( article=ArticleForResponse.from_orm( article.copy( update={ "favorited": True, "favorites_count": article.favorites_count + 1, }, ), ), ) raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=strings.ARTICLE_IS_ALREADY_FAVORITED, )
Example #12
Source File: test_asgi.py From schemathesis with MIT License | 6 votes |
def test_wsgi_app(testdir, cli): module = testdir.make_importable_pyfile( location=""" from fastapi import FastAPI from fastapi import HTTPException app = FastAPI() @app.get("/api/success") async def success(): return {"success": True} @app.get("/api/failure") async def failure(): raise HTTPException(status_code=500) return {"failure": True} """ ) result = cli.run("/openapi.json", "--app", f"{module.purebasename}:app") assert result.exit_code == ExitCode.TESTS_FAILED, result.stdout assert "1 passed, 1 failed in" in result.stdout
Example #13
Source File: bragi_client.py From idunn with Apache License 2.0 | 6 votes |
def raw_autocomplete(self, params, body=None): url = settings["BRAGI_BASE_URL"] + "/autocomplete" if body: response = await self.client.post(url, params=params, json=body) else: response = await self.client.get(url, params=params) if response.status_code != httpx.codes.ok: try: explain = response.json()["long"] except (IndexError, JSONDecodeError): explain = response.text logger.error( 'Request to Bragi returned with unexpected status %d: "%s"', response.status_code, explain, ) raise HTTPException(503, "Unexpected geocoder error") try: return response.json() except (JSONDecodeError, pydantic.ValidationError) as e: logger.exception("Autocomplete invalid response") raise HTTPException(503, "Invalid response from the geocoder")
Example #14
Source File: tutorial004.py From fastapi with MIT License | 6 votes |
def get_current_user(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, SECRET_KEY, algorithms=[ALGORITHM]) username: str = payload.get("sub") if username is None: raise credentials_exception token_data = TokenData(username=username) except PyJWTError: raise credentials_exception user = get_user(fake_users_db, username=token_data.username) if user is None: raise credentials_exception return user
Example #15
Source File: profiles.py From fastapi-realworld-example-app with MIT License | 6 votes |
def follow_for_user( profile: Profile = Depends(get_profile_by_username_from_path), user: User = Depends(get_current_user_authorizer()), profiles_repo: ProfilesRepository = Depends(get_repository(ProfilesRepository)), ) -> ProfileInResponse: if user.username == profile.username: raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=strings.UNABLE_TO_FOLLOW_YOURSELF, ) if profile.following: raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=strings.USER_IS_ALREADY_FOLLOWED, ) await profiles_repo.add_user_into_followers( target_user=profile, requested_user=user, ) return ProfileInResponse(profile=profile.copy(update={"following": True}))
Example #16
Source File: profiles.py From fastapi-realworld-example-app with MIT License | 6 votes |
def unsubscribe_from_user( profile: Profile = Depends(get_profile_by_username_from_path), user: User = Depends(get_current_user_authorizer()), profiles_repo: ProfilesRepository = Depends(get_repository(ProfilesRepository)), ) -> ProfileInResponse: if user.username == profile.username: raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=strings.UNABLE_TO_UNSUBSCRIBE_FROM_YOURSELF, ) if not profile.following: raise HTTPException( status_code=HTTP_400_BAD_REQUEST, detail=strings.USER_IS_NOT_FOLLOWED, ) await profiles_repo.remove_user_from_followers( target_user=profile, requested_user=user, ) return ProfileInResponse(profile=profile.copy(update={"following": False}))
Example #17
Source File: articles_resource.py From fastapi-realworld-example-app with MIT License | 6 votes |
def create_new_article( article_create: ArticleInCreate = Body(..., embed=True, alias="article"), user: User = Depends(get_current_user_authorizer()), articles_repo: ArticlesRepository = Depends(get_repository(ArticlesRepository)), ) -> ArticleInResponse: slug = get_slug_for_article(article_create.title) if await check_article_exists(articles_repo, slug): raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=strings.ARTICLE_ALREADY_EXISTS, ) article = await articles_repo.create_article( slug=slug, title=article_create.title, description=article_create.description, body=article_create.body, author=user, tags=article_create.tags, ) return ArticleInResponse(article=ArticleForResponse.from_orm(article))
Example #18
Source File: comments.py From fastapi-realworld-example-app with MIT License | 6 votes |
def get_comment_by_id_from_path( comment_id: int = Path(..., ge=1), article: Article = Depends(articles.get_article_by_slug_from_path), user: Optional[User] = Depends( authentication.get_current_user_authorizer(required=False), ), comments_repo: CommentsRepository = Depends( database.get_repository(CommentsRepository), ), ) -> Comment: try: return await comments_repo.get_comment_by_id( comment_id=comment_id, article=article, user=user, ) except EntityDoesNotExist: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=strings.COMMENT_DOES_NOT_EXIST, )
Example #19
Source File: rate_limiter.py From idunn with Apache License 2.0 | 5 votes |
def check_limit_per_client(self, request): client_id = request.headers.get("x-client-hash") or "default" try: with self.limit(client=client_id, ignore_redis_error=True): pass except TooManyRequestsException: raise HTTPException(status_code=429, detail="Too Many Requests")
Example #20
Source File: places.py From idunn with Apache License 2.0 | 5 votes |
def get_place( id: str, request: Request, background_tasks: BackgroundTasks, lang: str = None, type=None, verbosity=DEFAULT_VERBOSITY, ): """Main handler that returns the requested place""" verbosity = validate_verbosity(verbosity) lang = validate_lang(lang) try: place = place_from_id(id, type) except InvalidPlaceId as e: raise HTTPException(status_code=404, detail=e.message) except RedirectToPlaceId as e: path_prefix = request.headers.get("x-forwarded-prefix", "").rstrip("/") path = request.app.url_path_for("get_place", id=e.target_id) query = request.url.query return JSONResponse( status_code=303, headers={"location": str(URL(path=f"{path_prefix}{path}", query=query))}, content={"id": e.target_id}, ) log_place_request(place, request.headers) if settings["BLOCK_COVID_ENABLED"] and settings["COVID19_USE_REDIS_DATASET"]: background_tasks.add_task(covid19_osm_task) return place.load_place(lang, verbosity)
Example #21
Source File: places.py From idunn with Apache License 2.0 | 5 votes |
def get_place_latlon( lat: float, lon: float, lang: str = None, verbosity=DEFAULT_VERBOSITY ) -> Place: es = get_elasticsearch() verbosity = validate_verbosity(verbosity) lang = validate_lang(lang) try: closest_place = get_closest_place(lat, lon, es) except HTTPException: closest_place = None place = Latlon(lat, lon, closest_address=closest_place) return place.load_place(lang, verbosity)
Example #22
Source File: utils.py From idunn with Apache License 2.0 | 5 votes |
def fetch_es_place(id, es, type) -> dict: """Returns the raw Place data This function gets from Elasticsearch the entry corresponding to the given id. """ if type is None: index_name = PLACE_DEFAULT_INDEX elif type not in INDICES: raise HTTPException(status_code=400, detail=f"Wrong type parameter: type={type}") else: index_name = INDICES.get(type) try: es_places = es.search( index=index_name, body={"query": {"bool": {"filter": {"term": {"_id": id}}}}}, ignore_unavailable=True, _source_exclude=["boundary"], ) except ElasticsearchException as error: logger.warning(f"error with database: {error}") raise HTTPException(detail="database issue", status_code=503) es_place = es_places.get("hits", {}).get("hits", []) if len(es_place) == 0: if type is None: message = f"place '{id}' not found" else: message = f"place '{id}' not found with type={type}" raise PlaceNotFound(message=message) if len(es_place) > 1: logger.warning("Got multiple places with id %s", id) return es_place[0]
Example #23
Source File: utils.py From idunn with Apache License 2.0 | 5 votes |
def fetch_closest(lat, lon, max_distance, es): es_addrs = es.search( index=",".join([PLACE_ADDRESS_INDEX, PLACE_STREET_INDEX]), body={ "query": { "function_score": { "query": { "bool": { "filter": { "geo_distance": { "distance": "{}m".format(max_distance), "coord": {"lat": lat, "lon": lon}, "distance_type": "plane", } } } }, "boost_mode": "replace", "functions": [ { "gauss": { "coord": { "origin": {"lat": lat, "lon": lon}, "scale": "{}m".format(max_distance), } } } ], } }, "from": 0, "size": 1, }, ) es_addrs = es_addrs.get("hits", {}).get("hits", []) if len(es_addrs) == 0: raise HTTPException( status_code=404, detail=f"nothing around {lat}:{lon} within {max_distance}m..." ) return es_addrs[0]
Example #24
Source File: funcs.py From pytgbot with GNU General Public License v3.0 | 5 votes |
def send_media_group( token: str = TOKEN_VALIDATION, chat_id: Union[int, str] = Query(..., description='Unique identifier for the target chat or username of the target channel (in the format @channelusername)'), media: Json[Union[List['InputMediaPhotoModel'], List['InputMediaVideoModel']]] = Query(..., description='A JSON-serialized array describing photos and videos to be sent, must include 2-10 items'), disable_notification: Optional[bool] = Query(None, description='Sends the messages silently. Users will receive a notification with no sound.'), reply_to_message_id: Optional[int] = Query(None, description='If the messages are a reply, ID of the original message'), ) -> JSONableResponse: """ Use this method to send a group of photos or videos as an album. On success, an array of the sent Messages is returned. https://core.telegram.org/bots/api#sendmediagroup """ media: Union[List[InputMediaPhotoModel], List[InputMediaVideoModel]] = parse_obj_as( Union[List[InputMediaPhotoModel], List[InputMediaVideoModel]], obj=media, ) from .....main import _get_bot bot = await _get_bot(token) try: entity = await get_entity(bot, chat_id) except BotMethodInvalidError: assert isinstance(chat_id, int) or (isinstance(chat_id, str) and len(chat_id) > 0 and chat_id[0] == '@') entity = chat_id except ValueError: raise HTTPException(404, detail="chat not found?") # end try result = await bot.send_media_group( entity=entity, media=media, disable_notification=disable_notification, reply_to_message_id=reply_to_message_id, ) data = await to_web_api(result, bot) return r_success(data.to_array()) # end def
Example #25
Source File: closest.py From idunn with Apache License 2.0 | 5 votes |
def closest_address(lat: float, lon: float, lang=None, verbosity=DEFAULT_VERBOSITY) -> Address: if verbosity not in ALL_VERBOSITY_LEVELS: raise HTTPException( status_code=400, detail=f"Unknown verbosity '{verbosity}'. Accepted values are {ALL_VERBOSITY_LEVELS}", ) es = get_elasticsearch() if not lang: lang = settings["DEFAULT_LANGUAGE"] lang = lang.lower() place = get_closest_place(lat, lon, es) return place.load_place(lang, verbosity)
Example #26
Source File: funcs.py From pytgbot with GNU General Public License v3.0 | 5 votes |
def forward_message( token: str = TOKEN_VALIDATION, chat_id: Union[int, str] = Query(..., description='Unique identifier for the target chat or username of the target channel (in the format @channelusername)'), from_chat_id: Union[int, str] = Query(..., description='Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername)'), message_id: int = Query(..., description='Message identifier in the chat specified in from_chat_id'), disable_notification: Optional[bool] = Query(None, description='Sends the message silently. Users will receive a notification with no sound.'), ) -> JSONableResponse: """ Use this method to forward messages of any kind. On success, the sent Message is returned. https://core.telegram.org/bots/api#forwardmessage """ from .....main import _get_bot bot = await _get_bot(token) try: entity = await get_entity(bot, chat_id) except BotMethodInvalidError: assert isinstance(chat_id, int) or (isinstance(chat_id, str) and len(chat_id) > 0 and chat_id[0] == '@') entity = chat_id except ValueError: raise HTTPException(404, detail="chat not found?") # end try result = await bot.forward_message( entity=entity, from_chat_id=from_chat_id, message_id=message_id, disable_notification=disable_notification, ) data = await to_web_api(result, bot) return r_success(data.to_array()) # end def
Example #27
Source File: places_list.py From idunn with Apache License 2.0 | 5 votes |
def __init__(self, **data: Any): try: super().__init__(**data) except ValidationError as e: raise HTTPException( status_code=400, detail=e.errors(), )
Example #28
Source File: places_list.py From idunn with Apache License 2.0 | 5 votes |
def categories_or_raw_filters(cls, values): if values.get("raw_filter") and values.get("category"): raise HTTPException( status_code=400, detail="Both 'raw_filter' and 'category' parameters cannot be provided together", ) return values
Example #29
Source File: places_list.py From idunn with Apache License 2.0 | 5 votes |
def any_query_present(cls, values): if not any((values.get("raw_filter"), values.get("category"), values.get("q"))): raise HTTPException( status_code=400, detail="One of 'category', 'raw_filter' or 'q' parameter is required", ) return values
Example #30
Source File: profiles.py From fastapi-realworld-example-app with MIT License | 5 votes |
def get_profile_by_username_from_path( username: str = Path(..., min_length=1), user: Optional[User] = Depends(get_current_user_authorizer(required=False)), profiles_repo: ProfilesRepository = Depends(get_repository(ProfilesRepository)), ) -> Profile: try: return await profiles_repo.get_profile_by_username( username=username, requested_user=user, ) except EntityDoesNotExist: raise HTTPException( status_code=HTTP_404_NOT_FOUND, detail=strings.USER_DOES_NOT_EXIST_ERROR, )