Python starlette.status.HTTP_400_BAD_REQUEST Examples

The following are 17 code examples of starlette.status.HTTP_400_BAD_REQUEST(). 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 starlette.status , or try the search function .
Example #1
Source File: profiles.py    From fastapi-realworld-example-app with MIT License 6 votes vote down vote up
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 #2
Source File: events.py    From polyaxon with Apache License 2.0 6 votes vote down vote up
def process_operation_event(
    events_path: str,
    event_kind: str,
    event_name: str,
    orient: str = V1Events.ORIENT_CSV,
) -> Optional[Dict]:
    if not events_path or not os.path.exists(events_path):
        return None

    async with aiofiles.open(events_path, mode="r") as f:
        contents = await f.read()
        if contents:
            if orient == V1Events.ORIENT_CSV:
                return {"name": event_name, "kind": event_kind, "data": contents}
            if orient == V1Events.ORIENT_DICT:
                df = V1Events.read(
                    kind=event_kind, name=event_name, data=contents, parse_dates=False
                )
                return {"name": event_name, "kind": event_kind, "data": df.to_dict()}
            else:
                raise HTTPException(
                    detail="received an unrecognisable orient value {}.".format(orient),
                    status_code=status.HTTP_400_BAD_REQUEST,
                )
    return None 
Example #3
Source File: endpoints.py    From polyaxon with Apache License 2.0 6 votes vote down vote up
def get_run_events(request):
    run_uuid = request.path_params["run_uuid"]
    event_kind = request.path_params["event_kind"]
    force = to_bool(request.query_params.get("force"), handle_none=True)
    if event_kind not in V1ArtifactKind.allowable_values:
        raise HTTPException(
            detail="received an unrecognisable event {}.".format(event_kind),
            status_code=status.HTTP_400_BAD_REQUEST,
        )
    event_names = request.query_params["names"]
    orient = request.query_params.get("orient")
    orient = orient or V1Events.ORIENT_DICT
    event_names = {e for e in event_names.split(",") if e} if event_names else set([])
    events = await get_archived_operation_events(
        run_uuid=run_uuid,
        event_kind=event_kind,
        event_names=event_names,
        orient=orient,
        check_cache=not force,
    )
    return UJSONResponse({"data": events}) 
Example #4
Source File: endpoints.py    From polyaxon with Apache License 2.0 6 votes vote down vote up
def get_multi_runs_events(request):
    event_kind = request.path_params["event_kind"]
    force = to_bool(request.query_params.get("force"), handle_none=True)
    if event_kind not in V1ArtifactKind.allowable_values:
        raise HTTPException(
            detail="received an unrecognisable event {}.".format(event_kind),
            status_code=status.HTTP_400_BAD_REQUEST,
        )
    run_uuids = request.query_params["runs"]
    event_names = request.query_params["names"]
    orient = request.query_params.get("orient")
    orient = orient or V1Events.ORIENT_DICT
    event_names = {e for e in event_names.split(",") if e} if event_names else set([])
    run_uuids = {e for e in run_uuids.split(",") if e} if run_uuids else set([])
    events = await get_archived_operations_events(
        run_uuids=run_uuids,
        event_kind=event_kind,
        event_names=event_names,
        orient=orient,
        check_cache=not force,
    )
    return UJSONResponse({"data": events}) 
Example #5
Source File: vps.py    From LuWu with Apache License 2.0 6 votes vote down vote up
def destroy_vps_server(db: Session = Depends(get_db), *, vps_id: int):
    # check exists of relation data
    relation_data_exists = crud_vps.check_relation_data_exists(
        db_session=db,
        id=vps_id,
        relation_key_list=['team_servers', 'redirector_c2s', 'smtp_servers']
    )
    if relation_data_exists:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="exists relation data",
        )

    destroy_task = celery_app.send_task(
        "destroy_vps", args=[vps_id]
    )
    with allow_join_result():
        destroy_task.get()

    destroy_result = {
        'status': crud_vps.remove(db_session=db, id=vps_id)
    }

    return dict(result=destroy_result) 
Example #6
Source File: test_exceptions.py    From fastapi_contrib with MIT License 6 votes vote down vote up
def test_http_exception():
    detail = "Random HTTP error happened."
    status_code = status.HTTP_400_BAD_REQUEST
    error_code = 999
    with pytest.raises(HTTPException) as excinfo:
        raise HTTPException(
            status_code=status_code,
            error_code=error_code,
            detail=detail,
            fields=[{"field": "because of this."}],
        )

    exc = excinfo.value
    assert exc.error_code == error_code
    assert exc.detail == detail
    assert exc.status_code == status_code
    assert exc.fields == [{"field": "because of this."}] 
Example #7
Source File: articles_common.py    From fastapi-realworld-example-app with MIT License 6 votes vote down vote up
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 #8
Source File: articles_resource.py    From fastapi-realworld-example-app with MIT License 6 votes vote down vote up
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 #9
Source File: profiles.py    From fastapi-realworld-example-app with MIT License 6 votes vote down vote up
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 #10
Source File: authentication.py    From fastapi-realworld-example-app with MIT License 5 votes vote down vote up
def register(
    user_create: UserInCreate = Body(..., embed=True, alias="user"),
    users_repo: UsersRepository = Depends(get_repository(UsersRepository)),
) -> UserInResponse:
    if await check_username_is_taken(users_repo, user_create.username):
        raise HTTPException(
            status_code=HTTP_400_BAD_REQUEST, detail=strings.USERNAME_TAKEN,
        )

    if await check_email_is_taken(users_repo, user_create.email):
        raise HTTPException(
            status_code=HTTP_400_BAD_REQUEST, detail=strings.EMAIL_TAKEN,
        )

    user = await users_repo.create_user(**user_create.dict())

    token = jwt.create_access_token_for_user(user, str(config.SECRET_KEY))
    return UserInResponse(
        user=UserWithToken(
            username=user.username,
            email=user.email,
            bio=user.bio,
            image=user.image,
            token=token,
        ),
    ) 
Example #11
Source File: authentication.py    From fastapi-realworld-example-app with MIT License 5 votes vote down vote up
def login(
    user_login: UserInLogin = Body(..., embed=True, alias="user"),
    users_repo: UsersRepository = Depends(get_repository(UsersRepository)),
) -> UserInResponse:
    wrong_login_error = HTTPException(
        status_code=HTTP_400_BAD_REQUEST, detail=strings.INCORRECT_LOGIN_INPUT,
    )

    try:
        user = await users_repo.get_user_by_email(email=user_login.email)
    except EntityDoesNotExist as existence_error:
        raise wrong_login_error from existence_error

    if not user.check_password(user_login.password):
        raise wrong_login_error

    token = jwt.create_access_token_for_user(user, str(config.SECRET_KEY))
    return UserInResponse(
        user=UserWithToken(
            username=user.username,
            email=user.email,
            bio=user.bio,
            image=user.image,
            token=token,
        ),
    ) 
Example #12
Source File: main.py    From LuWu with Apache License 2.0 5 votes vote down vote up
def http_exception_handler(request: Request, exc: HTTPException):
    failed_res = BaseFailedResponseModel(errors=[exc.detail]).dict()
    status_code = exc.status_code or status.HTTP_400_BAD_REQUEST
    return JSONResponse(failed_res, status_code=status_code) 
Example #13
Source File: view.py    From pygraphy with MIT License 5 votes vote down vote up
def post(self, request):
        content_type = request.headers.get("Content-Type", "")

        if "application/json" in content_type:
            data = await request.json()
        elif "application/graphql" in content_type:
            body = await request.body()
            text = body.decode()
            data = {"query": text}
        elif "query" in request.query_params:
            data = request.query_params
        else:
            return PlainTextResponse(
                "Unsupported Media Type",
                status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
            )

        try:
            query = data["query"]
            variables = data.get("variables")
        except KeyError:
            return PlainTextResponse(
                "No GraphQL query found in the request",
                status_code=status.HTTP_400_BAD_REQUEST,
            )

        result = await self.execute(
            query, variables=variables, request=request
        )
        status_code = status.HTTP_200_OK
        return Response(
            json.dumps(result, cls=GraphQLEncoder),
            status_code=status_code,
            media_type='application/json'
        ) 
Example #14
Source File: logs.py    From polyaxon with Apache License 2.0 5 votes vote down vote up
def upload_logs(run_uuid: str, logs: List[V1Log]):
    if not settings.AGENT_CONFIG.artifacts_store:
        raise HTTPException(
            detail="Run's logs was not collected, resource was not found.",
            status_code=status.HTTP_400_BAD_REQUEST,
        )
    for c_logs in V1Logs.chunk_logs(logs):
        last_file = datetime.timestamp(c_logs.logs[-1].timestamp)
        subpath = "{}/plxlogs/{}".format(run_uuid, last_file)
        await upload_data(subpath=subpath, data=c_logs.to_dict(dump=True)) 
Example #15
Source File: endpoints.py    From polyaxon with Apache License 2.0 5 votes vote down vote up
def collect_logs(request):
    owner = request.path_params["owner"]
    project = request.path_params["project"]
    run_uuid = request.path_params["run_uuid"]
    resource_name = get_resource_name(run_uuid=run_uuid)
    operation = get_run_instance(owner=owner, project=project, run_uuid=run_uuid)
    k8s_manager = AsyncK8SManager(
        namespace=settings.CLIENT_CONFIG.namespace,
        in_cluster=settings.CLIENT_CONFIG.in_cluster,
    )
    await k8s_manager.setup()
    k8s_operation = await get_k8s_operation(
        k8s_manager=k8s_manager, resource_name=resource_name
    )
    if not k8s_operation:
        raise HTTPException(
            detail="Run's logs was not collected, resource was not found.",
            status_code=status.HTTP_400_BAD_REQUEST,
        )
    operation_logs, _ = await get_k8s_operation_logs(
        operation=operation, k8s_manager=k8s_manager, last_time=None
    )
    if k8s_manager:
        await k8s_manager.close()
    if not operation_logs:
        return Response()

    logs = operation_logs
    task = BackgroundTask(upload_logs, run_uuid=run_uuid, logs=logs)
    return Response(background=task) 
Example #16
Source File: endpoints.py    From polyaxon with Apache License 2.0 5 votes vote down vote up
def notify(request):
    namespace = request.path_params["namespace"]
    owner = request.path_params["owner"]
    project = request.path_params["project"]
    run_uuid = request.path_params["run_uuid"]
    body = await request.json()
    run_name = body.get("name")
    condition = body.get("condition")
    if not condition:
        raise HTTPException(
            detail="Received a notification request without condition.",
            status_code=status.HTTP_400_BAD_REQUEST,
        )
    condition = V1StatusCondition.get_condition(**condition)
    connections = body.get("connections")
    if not connections:
        raise HTTPException(
            detail="Received a notification request without connections.",
            status_code=status.HTTP_400_BAD_REQUEST,
        )

    if not settings.AGENT_CONFIG.notification_connections:
        raise HTTPException(
            detail="Run's logs was not collected, resource was not found.",
            status_code=status.HTTP_400_BAD_REQUEST,
        )

    task = BackgroundTask(
        notify_run,
        namespace=namespace,
        owner=owner,
        project=project,
        run_uuid=run_uuid,
        run_name=run_name,
        condition=condition,
        connections=connections,
    )
    return Response(background=task) 
Example #17
Source File: users.py    From fastapi-realworld-example-app with MIT License 5 votes vote down vote up
def update_current_user(
    user_update: UserInUpdate = Body(..., embed=True, alias="user"),
    current_user: User = Depends(get_current_user_authorizer()),
    users_repo: UsersRepository = Depends(get_repository(UsersRepository)),
) -> UserInResponse:
    if user_update.username and user_update.username != current_user.username:
        if await check_username_is_taken(users_repo, user_update.username):
            raise HTTPException(
                status_code=HTTP_400_BAD_REQUEST, detail=strings.USERNAME_TAKEN,
            )

    if user_update.email and user_update.email != current_user.email:
        if await check_email_is_taken(users_repo, user_update.email):
            raise HTTPException(
                status_code=HTTP_400_BAD_REQUEST, detail=strings.EMAIL_TAKEN,
            )

    user = await users_repo.update_user(user=current_user, **user_update.dict())

    token = jwt.create_access_token_for_user(user, str(config.SECRET_KEY))
    return UserInResponse(
        user=UserWithToken(
            username=user.username,
            email=user.email,
            bio=user.bio,
            image=user.image,
            token=token,
        ),
    )