async def test_set_cookie(): response = PlainTextResponse("Hello, world!", media_type="text/plain") response.set_cookie( "mycookie", "myvalue", max_age=10, expires=10, path="/", domain="localhost", secure=True, httponly=True, samesite="none", ) async with httpx.AsyncClient(app=response, base_url="http://testServer/") as client: response = await client.get("/") assert response.text == "Hello, world!"
async def upload(request: Request) -> Response: """Load multipart data and store it as a file.""" if request.method != "POST": return Response(405) try: formdata = await request.form except HTTPException as exc: return Response(exc.status_code, exc.headers) if "file" not in formdata: return PlainTextResponse("ERROR", status_code=400) filepath = f"/tmp/{uuid4().hex}" await formdata["file"].asave(filepath) return PlainTextResponse(filepath)
async def test_hosts(): async with httpx.AsyncClient( app=Hosts( ("testServer", PlainTextResponse("testServer")), (".*", PlainTextResponse("default host")), ), base_url="http://testServer/", ) as client: assert ( await client.get("/", headers={"host": "testServer"}) ).text == "testServer" assert ( await client.get("/", headers={"host": "hhhhhhh"}) ).text == "default host" assert ( await client.get("/", headers={"host": "qwe\ndsf"}) ).text == "Invalid host"
async def api(request: Request) -> Response: """Check headers for authorization, load JSON/query data and return as JSON.""" if request.method != "PUT": return Response(405) if request.headers.get("authorization") is None: return PlainTextResponse("ERROR", status_code=401) return JSONResponse({ "params": request.path_params, "query": dict(request.query_params), "data": await request.json, })
async def http_exception(exc: HTTPException) -> HttpResponse: if exc.status_code in {204, 304}: return HttpResponse(status_code=exc.status_code, headers=exc.headers) return PlainTextResponse( content=( exc.content if isinstance(exc.content, (bytes, str)) else HTTPStatus(exc.status_code).description ), status_code=exc.status_code, headers=exc.headers, )
async def app(scope, receive, send): request = Request(scope, receive) response = PlainTextResponse("Hello, world!", media_type="text/plain") if request.cookies.get("mycookie"): response.delete_cookie("mycookie") else: response.set_cookie("mycookie", "myvalue") await response(scope, receive, send)
async def app(scope, receive, send): request = Request(scope, receive) mycookie = request.cookies.get("mycookie") if mycookie: response = PlainTextResponse(mycookie) else: response = PlainTextResponse("Hello, world!") response.set_cookie("mycookie", "Hello, cookies!") await response(scope, receive, send)
async def test_router(): @request_response async def path(request: Request) -> Response: return JSONResponse(request.path_params) @request_response async def redirect(request: Request) -> Response: return RedirectResponse("/cat") router = Router( ("/", PlainTextResponse("homepage")), ("/redirect", redirect), ("/{path}", path), ) async with httpx.AsyncClient(app=router, base_url="http://testServer/") as client: assert (await client.get("/")).text == "homepage" assert (await client.get("/baize")).json() == {"path": "baize"} assert (await client.get("/baize/")).status_code == 404 assert (await (client.get("/redirect"))).headers["location"] == "/cat"
def _plain_text( body: typing.Union[str, bytes], status: int = 200, headers: typing.Mapping[str, str] = None, ) -> HttpResponse: return PlainTextResponse(body, status, headers)
async def user(request): return PlainTextResponse(request.path_params["user_id"])
async def homepage(request): return PlainTextResponse("")
async def userinfo(request): return PlainTextResponse("")
next_call: Callable[[Request], Awaitable[Response]]) -> Response: start_time = time.time() response = await next_call(request) end_time = time.time() response.headers["x-time"] = str(round((end_time - start_time) * 1000)) return response @request_response @timer async def sayhi(request: Request) -> Response: return PlainTextResponse("hi, " + request.path_params["name"]) @request_response @timer async def echo(request: Request) -> Response: return PlainTextResponse(await request.body) application = Router( ("/", PlainTextResponse("homepage")), ("/echo", echo), ("/sayhi/{name}", sayhi), ) if __name__ == "__main__": import uvicorn uvicorn.run(application, interface="asgi3", port=8000)
async def sayhi(request: Request) -> Response: return PlainTextResponse("hi, " + request.path_params["name"])
async def view(request: Request) -> Response: return PlainTextResponse(await request.body)
async def app(scope, receive, send): if scope["path"] == "/": response = PlainTextResponse("hello, world") else: response = RedirectResponse("/") await response(scope, receive, send)
async def request_validation_error(exc: RequestValidationError) -> HttpResponse: return PlainTextResponse( exc.json(), status_code=422, media_type="application/json" )
async def root(request: Request) -> Response: return PlainTextResponse(request.get("root_path", ""))
async def app(scope, receive, send): headers = {"x-header-1": "123", "x-header-2": "456"} response = PlainTextResponse("hello, world", headers=headers) response.headers["x-header-2"] = "789" await response(scope, receive, send)
async def path(request: Request) -> Response: return PlainTextResponse(request["path"])