当前位置: 首页>>代码示例>>Python>>正文


Python fastapi.FastAPI方法代码示例

本文整理汇总了Python中fastapi.FastAPI方法的典型用法代码示例。如果您正苦于以下问题:Python fastapi.FastAPI方法的具体用法?Python fastapi.FastAPI怎么用?Python fastapi.FastAPI使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在fastapi的用法示例。


在下文中一共展示了fastapi.FastAPI方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_wsgi_app

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import FastAPI [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: get_application

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import FastAPI [as 别名]
def get_application() -> FastAPI:
    application = FastAPI(title=PROJECT_NAME, debug=DEBUG, version=VERSION)

    application.add_middleware(
        CORSMiddleware,
        allow_origins=ALLOWED_HOSTS or ["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    application.add_event_handler("startup", create_start_app_handler(application))
    application.add_event_handler("shutdown", create_stop_app_handler(application))

    application.add_exception_handler(HTTPException, http_error_handler)
    application.add_exception_handler(RequestValidationError, http422_error_handler)

    application.include_router(api_router, prefix=API_PREFIX)

    return application 
开发者ID:nsidnev,项目名称:fastapi-realworld-example-app,代码行数:22,代码来源:main.py

示例3: test_user_that_does_not_follows_another_will_receive_profile_without_follow

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import FastAPI [as 别名]
def test_user_that_does_not_follows_another_will_receive_profile_without_follow(
    app: FastAPI, authorized_client: AsyncClient, pool: Pool
) -> None:
    async with pool.acquire() as conn:
        users_repo = UsersRepository(conn)
        user = await users_repo.create_user(
            username="user_for_following",
            email="test-for-following@email.com",
            password="password",
        )

    response = await authorized_client.get(
        app.url_path_for("profiles:get-profile", username=user.username)
    )
    profile = ProfileInResponse(**response.json())
    assert profile.profile.username == user.username
    assert not profile.profile.following 
开发者ID:nsidnev,项目名称:fastapi-realworld-example-app,代码行数:19,代码来源:test_profiles.py

示例4: test_user_that_follows_another_will_receive_profile_with_follow

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import FastAPI [as 别名]
def test_user_that_follows_another_will_receive_profile_with_follow(
    app: FastAPI, authorized_client: AsyncClient, pool: Pool, test_user: UserInDB
) -> None:
    async with pool.acquire() as conn:
        users_repo = UsersRepository(conn)
        user = await users_repo.create_user(
            username="user_for_following",
            email="test-for-following@email.com",
            password="password",
        )

        profiles_repo = ProfilesRepository(conn)
        await profiles_repo.add_user_into_followers(
            target_user=user, requested_user=test_user
        )

    response = await authorized_client.get(
        app.url_path_for("profiles:get-profile", username=user.username)
    )
    profile = ProfileInResponse(**response.json())
    assert profile.profile.username == user.username
    assert profile.profile.following 
开发者ID:nsidnev,项目名称:fastapi-realworld-example-app,代码行数:24,代码来源:test_profiles.py

示例5: test_user_success_registration

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import FastAPI [as 别名]
def test_user_success_registration(
    app: FastAPI, client: AsyncClient, pool: Pool
) -> None:
    email, username, password = "test@test.com", "username", "password"
    registration_json = {
        "user": {"email": email, "username": username, "password": password}
    }
    response = await client.post(
        app.url_path_for("auth:register"), json=registration_json
    )
    assert response.status_code == HTTP_201_CREATED

    async with pool.acquire() as conn:
        repo = UsersRepository(conn)
        user = await repo.get_user_by_email(email=email)
        assert user.email == email
        assert user.username == username
        assert user.check_password(password) 
开发者ID:nsidnev,项目名称:fastapi-realworld-example-app,代码行数:20,代码来源:test_registration.py

示例6: test_failed_user_registration_when_some_credentials_are_taken

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import FastAPI [as 别名]
def test_failed_user_registration_when_some_credentials_are_taken(
    app: FastAPI,
    client: AsyncClient,
    test_user: UserInDB,
    credentials_part: str,
    credentials_value: str,
) -> None:
    registration_json = {
        "user": {
            "email": "test@test.com",
            "username": "username",
            "password": "password",
        }
    }
    registration_json["user"][credentials_part] = credentials_value

    response = await client.post(
        app.url_path_for("auth:register"), json=registration_json
    )
    assert response.status_code == HTTP_400_BAD_REQUEST 
开发者ID:nsidnev,项目名称:fastapi-realworld-example-app,代码行数:22,代码来源:test_registration.py

示例7: test_user_can_change_password

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import FastAPI [as 别名]
def test_user_can_change_password(
    app: FastAPI,
    authorized_client: AsyncClient,
    test_user: UserInDB,
    token: str,
    pool: Pool,
) -> None:
    response = await authorized_client.put(
        app.url_path_for("users:update-current-user"),
        json={"user": {"password": "new_password"}},
    )
    assert response.status_code == status.HTTP_200_OK
    user_profile = UserInResponse(**response.json())

    async with pool.acquire() as connection:
        users_repo = UsersRepository(connection)
        user = await users_repo.get_user_by_username(
            username=user_profile.user.username
        )

    assert user.check_password("new_password") 
开发者ID:nsidnev,项目名称:fastapi-realworld-example-app,代码行数:23,代码来源:test_users.py

示例8: test_user_can_not_take_already_used_credentials

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import FastAPI [as 别名]
def test_user_can_not_take_already_used_credentials(
    app: FastAPI,
    authorized_client: AsyncClient,
    pool: Pool,
    token: str,
    credentials_part: str,
    credentials_value: str,
) -> None:
    user_dict = {
        "username": "not_taken_username",
        "password": "password",
        "email": "free_email@email.com",
    }
    user_dict.update({credentials_part: credentials_value})
    async with pool.acquire() as conn:
        users_repo = UsersRepository(conn)
        await users_repo.create_user(**user_dict)

    response = await authorized_client.put(
        app.url_path_for("users:update-current-user"),
        json={"user": {credentials_part: credentials_value}},
    )
    assert response.status_code == status.HTTP_400_BAD_REQUEST 
开发者ID:nsidnev,项目名称:fastapi-realworld-example-app,代码行数:25,代码来源:test_users.py

示例9: test_user_can_add_comment_for_article

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import FastAPI [as 别名]
def test_user_can_add_comment_for_article(
    app: FastAPI, authorized_client: AsyncClient, test_article: Article
) -> None:
    created_comment_response = await authorized_client.post(
        app.url_path_for("comments:create-comment-for-article", slug=test_article.slug),
        json={"comment": {"body": "comment"}},
    )

    created_comment = CommentInResponse(**created_comment_response.json())

    comments_for_article_response = await authorized_client.get(
        app.url_path_for("comments:get-comments-for-article", slug=test_article.slug)
    )

    comments = ListOfCommentsInResponse(**comments_for_article_response.json())

    assert created_comment.comment == comments.comments[0] 
开发者ID:nsidnev,项目名称:fastapi-realworld-example-app,代码行数:19,代码来源:test_comments.py

示例10: test_user_can_delete_own_comment

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import FastAPI [as 别名]
def test_user_can_delete_own_comment(
    app: FastAPI, authorized_client: AsyncClient, test_article: Article
) -> None:
    created_comment_response = await authorized_client.post(
        app.url_path_for("comments:create-comment-for-article", slug=test_article.slug),
        json={"comment": {"body": "comment"}},
    )

    created_comment = CommentInResponse(**created_comment_response.json())

    await authorized_client.delete(
        app.url_path_for(
            "comments:delete-comment-from-article",
            slug=test_article.slug,
            comment_id=str(created_comment.comment.id_),
        )
    )

    comments_for_article_response = await authorized_client.get(
        app.url_path_for("comments:get-comments-for-article", slug=test_article.slug)
    )

    comments = ListOfCommentsInResponse(**comments_for_article_response.json())

    assert len(comments.comments) == 0 
开发者ID:nsidnev,项目名称:fastapi-realworld-example-app,代码行数:27,代码来源:test_comments.py

示例11: test_user_can_not_delete_not_authored_comment

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import FastAPI [as 别名]
def test_user_can_not_delete_not_authored_comment(
    app: FastAPI, authorized_client: AsyncClient, test_article: Article, pool: Pool
) -> None:
    async with pool.acquire() as connection:
        users_repo = UsersRepository(connection)
        user = await users_repo.create_user(
            username="test_author", email="author@email.com", password="password"
        )
        comments_repo = CommentsRepository(connection)
        comment = await comments_repo.create_comment_for_article(
            body="tmp", article=test_article, user=user
        )

    forbidden_response = await authorized_client.delete(
        app.url_path_for(
            "comments:delete-comment-from-article",
            slug=test_article.slug,
            comment_id=str(comment.id_),
        )
    )

    assert forbidden_response.status_code == status.HTTP_403_FORBIDDEN 
开发者ID:nsidnev,项目名称:fastapi-realworld-example-app,代码行数:24,代码来源:test_comments.py

示例12: setup_exception_handlers

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import FastAPI [as 别名]
def setup_exception_handlers(app: FastAPI) -> None:
    """
    Helper function to setup exception handlers for app.
    Use during app startup as follows:

    .. code-block:: python

        app = FastAPI()

        @app.on_event('startup')
        async def startup():
            setup_exception_handlers(app)

    :param app: app object, instance of FastAPI
    :return: None
    """
    app.add_exception_handler(StarletteHTTPException, http_exception_handler)
    app.add_exception_handler(
        RequestValidationError, validation_exception_handler
    )
    app.add_exception_handler(404, not_found_error_handler)
    app.add_exception_handler(500, internal_server_error_handler) 
开发者ID:identixone,项目名称:fastapi_contrib,代码行数:24,代码来源:exception_handlers.py

示例13: test_cli_run_output_success

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import FastAPI [as 别名]
def test_cli_run_output_success(testdir, cli, workers):
    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}

            """
    )
    result = cli.run(
        "/openapi.json", "--app", f"{module.purebasename}:app", f"--workers={workers}", "--show-errors-tracebacks"
    )

    assert result.exit_code == ExitCode.OK, result.stdout
    lines = result.stdout.split("\n")
    assert lines[7] == f"Workers: {workers}"
    if workers == 1:
        assert lines[10].startswith("GET /api/success .")
    else:
        assert lines[10] == "."
    assert " HYPOTHESIS OUTPUT " not in result.stdout
    assert " SUMMARY " in result.stdout

    lines = result.stdout.strip().split("\n")
    last_line = lines[-1]
    assert "== 1 passed in " in last_line
    # And the running time is a small positive number
    time = float(last_line.split(" ")[-2].replace("s", ""))
    assert 0 <= time < 5 
开发者ID:kiwicom,项目名称:schemathesis,代码行数:36,代码来源:test_asgi.py

示例14: create_app

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import FastAPI [as 别名]
def create_app():
    app = FastAPI()

    @app.get("/users")
    async def root():
        return {"success": True}

    return app 
开发者ID:kiwicom,项目名称:schemathesis,代码行数:10,代码来源:__init__.py

示例15: server

# 需要导入模块: import fastapi [as 别名]
# 或者: from fastapi import FastAPI [as 别名]
def server(model):
    app = FastAPI()

    input_features = {
        f['name'] for f in model.model_definition['input_features']
    }

    @app.get('/')
    def check_health():
        return JSONResponse({"message": "Ludwig server is up"})

    @app.post('/predict')
    async def predict(request: Request):
        form = await request.form()
        files, entry = convert_input(form)

        try:
            if (entry.keys() & input_features) != input_features:
                return JSONResponse(ALL_FEATURES_PRESENT_ERROR,
                                    status_code=400)
            try:
                resp = model.predict(data_dict=[entry]).to_dict('records')[0]
                return JSONResponse(resp)
            except Exception as e:
                logger.error("Error: {}".format(str(e)))
                return JSONResponse(COULD_NOT_RUN_INFERENCE_ERROR,
                                    status_code=500)
        finally:
            for f in files:
                os.remove(f.name)

    return app 
开发者ID:uber,项目名称:ludwig,代码行数:34,代码来源:serve.py


注:本文中的fastapi.FastAPI方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。