Python源码示例:fastapi.FastAPI()
示例1
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
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
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
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
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
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
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
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
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
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
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
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
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
def create_app():
app = FastAPI()
@app.get("/users")
async def root():
return {"success": True}
return app
示例15
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
示例16
def test_invalid_response_model_raises():
with pytest.raises(FastAPIError):
app = FastAPI()
@app.get("/", response_model=NonPydanticModel)
def read_root():
pass # pragma: nocover
示例17
def test_invalid_response_model_sub_type_raises():
with pytest.raises(FastAPIError):
app = FastAPI()
@app.get("/", response_model=List[NonPydanticModel])
def read_root():
pass # pragma: nocover
示例18
def test_invalid_response_model_in_responses_raises():
with pytest.raises(FastAPIError):
app = FastAPI()
@app.get("/", responses={"500": {"model": NonPydanticModel}})
def read_root():
pass # pragma: nocover
示例19
def test_invalid_response_model_sub_type_in_responses_raises():
with pytest.raises(FastAPIError):
app = FastAPI()
@app.get("/", responses={"500": {"model": List[NonPydanticModel]}})
def read_root():
pass # pragma: nocover
示例20
def test_invalid_sequence():
with pytest.raises(AssertionError):
app = FastAPI()
class Item(BaseModel):
title: str
@app.get("/items/")
def read_items(q: List[Item] = Query(None)):
pass # pragma: no cover
示例21
def test_invalid_dict():
with pytest.raises(AssertionError):
app = FastAPI()
class Item(BaseModel):
title: str
@app.get("/items/")
def read_items(q: Dict[str, Item] = Query(None)):
pass # pragma: no cover
示例22
def test_invalid_simple_dict():
with pytest.raises(AssertionError):
app = FastAPI()
class Item(BaseModel):
title: str
@app.get("/items/")
def read_items(q: Optional[dict] = Query(None)):
pass # pragma: no cover
示例23
def test_signatures_consistency():
base_sig = inspect.signature(APIRouter.get)
for method_name in method_names:
router_method = getattr(APIRouter, method_name)
app_method = getattr(FastAPI, method_name)
router_sig = inspect.signature(router_method)
app_sig = inspect.signature(app_method)
param: inspect.Parameter
for key, param in base_sig.parameters.items():
router_param: inspect.Parameter = router_sig.parameters[key]
app_param: inspect.Parameter = app_sig.parameters[key]
assert param.annotation == router_param.annotation
assert param.annotation == app_param.annotation
assert param.default == router_param.default
assert param.default == app_param.default
示例24
def test_invalid_sequence():
with pytest.raises(AssertionError):
app = FastAPI()
class Item(BaseModel):
title: str
@app.get("/items/{id}")
def read_items(id: List[Item]):
pass # pragma: no cover
示例25
def test_invalid_tuple():
with pytest.raises(AssertionError):
app = FastAPI()
class Item(BaseModel):
title: str
@app.get("/items/{id}")
def read_items(id: Tuple[Item, Item]):
pass # pragma: no cover
示例26
def test_invalid_simple_list():
with pytest.raises(AssertionError):
app = FastAPI()
@app.get("/items/{id}")
def read_items(id: list):
pass # pragma: no cover
示例27
def test_invalid_simple_tuple():
with pytest.raises(AssertionError):
app = FastAPI()
@app.get("/items/{id}")
def read_items(id: tuple):
pass # pragma: no cover
示例28
def test_invalid_simple_set():
with pytest.raises(AssertionError):
app = FastAPI()
@app.get("/items/{id}")
def read_items(id: set):
pass # pragma: no cover
示例29
def test_invalid_simple_dict():
with pytest.raises(AssertionError):
app = FastAPI()
@app.get("/items/{id}")
def read_items(id: dict):
pass # pragma: no cover
示例30
def get_user(bucket: Bucket, username: str):
doc_id = f"userprofile::{username}"
result = bucket.get(doc_id, quiet=True)
if not result.value:
return None
user = UserInDB(**result.value)
return user
# FastAPI specific code