本文整理汇总了Python中fastapi.HTTPException方法的典型用法代码示例。如果您正苦于以下问题:Python fastapi.HTTPException方法的具体用法?Python fastapi.HTTPException怎么用?Python fastapi.HTTPException使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类fastapi
的用法示例。
在下文中一共展示了fastapi.HTTPException方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_wsgi_app
# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import HTTPException [as 别名]
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
示例2: create_user
# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import HTTPException [as 别名]
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
示例3: update_user
# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import HTTPException [as 别名]
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
示例4: update_item
# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import HTTPException [as 别名]
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
示例5: login
# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import HTTPException [as 别名]
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",
}
示例6: recover_password
# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import HTTPException [as 别名]
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"}
示例7: reset_password
# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import HTTPException [as 别名]
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"}
示例8: get_current_user
# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import HTTPException [as 别名]
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
示例9: get_closest_place
# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import HTTPException [as 别名]
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"])
示例10: get_directions_with_coordinates
# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import HTTPException [as 别名]
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
)
示例11: raw_autocomplete
# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import HTTPException [as 别名]
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")
示例12: follow_for_user
# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import HTTPException [as 别名]
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}))
示例13: unsubscribe_from_user
# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import HTTPException [as 别名]
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}))
示例14: create_new_article
# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import HTTPException [as 别名]
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))
示例15: mark_article_as_favorite
# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import HTTPException [as 别名]
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,
)