本文整理匯總了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
示例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
示例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
示例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
示例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)
示例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
示例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")
示例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
示例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]
示例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
示例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
示例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)
示例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
示例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
示例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