當前位置: 首頁>>代碼示例>>Python>>正文


Python fastapi.HTTPException方法代碼示例

本文整理匯總了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 
開發者ID:kiwicom,項目名稱:schemathesis,代碼行數:23,代碼來源:test_asgi.py

示例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 
開發者ID:tiangolo,項目名稱:full-stack-fastapi-couchbase,代碼行數:23,代碼來源:users.py

示例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 
開發者ID:tiangolo,項目名稱:full-stack-fastapi-couchbase,代碼行數:21,代碼來源:users.py

示例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 
開發者ID:tiangolo,項目名稱:full-stack-fastapi-couchbase,代碼行數:23,代碼來源:items.py

示例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",
    } 
開發者ID:tiangolo,項目名稱:full-stack-fastapi-couchbase,代碼行數:21,代碼來源:login.py

示例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"} 
開發者ID:tiangolo,項目名稱:full-stack-fastapi-couchbase,代碼行數:19,代碼來源:login.py

示例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"} 
開發者ID:tiangolo,項目名稱:full-stack-fastapi-couchbase,代碼行數:21,代碼來源:login.py

示例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 
開發者ID:tiangolo,項目名稱:fastapi,代碼行數:20,代碼來源:tutorial004.py

示例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"]) 
開發者ID:QwantResearch,項目名稱:idunn,代碼行數:24,代碼來源:closest.py

示例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
    ) 
開發者ID:QwantResearch,項目名稱:idunn,代碼行數:21,代碼來源:directions.py

示例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") 
開發者ID:QwantResearch,項目名稱:idunn,代碼行數:26,代碼來源:bragi_client.py

示例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})) 
開發者ID:nsidnev,項目名稱:fastapi-realworld-example-app,代碼行數:22,代碼來源:profiles.py

示例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})) 
開發者ID:nsidnev,項目名稱:fastapi-realworld-example-app,代碼行數:23,代碼來源:profiles.py

示例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)) 
開發者ID:nsidnev,項目名稱:fastapi-realworld-example-app,代碼行數:23,代碼來源:articles_resource.py

示例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,
    ) 
開發者ID:nsidnev,項目名稱:fastapi-realworld-example-app,代碼行數:25,代碼來源:articles_common.py


注:本文中的fastapi.HTTPException方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。