Beispiel #1
0
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!"
Beispiel #2
0
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)
Beispiel #3
0
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"
Beispiel #4
0
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,
    })
Beispiel #5
0
    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,
        )
Beispiel #6
0
 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)
Beispiel #7
0
    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)
Beispiel #8
0
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"
Beispiel #9
0
def _plain_text(
    body: typing.Union[str, bytes],
    status: int = 200,
    headers: typing.Mapping[str, str] = None,
) -> HttpResponse:
    return PlainTextResponse(body, status, headers)
Beispiel #10
0
async def user(request):
    return PlainTextResponse(request.path_params["user_id"])
Beispiel #11
0
async def homepage(request):
    return PlainTextResponse("")
Beispiel #12
0
async def userinfo(request):
    return PlainTextResponse("")
Beispiel #13
0
        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)
Beispiel #14
0
async def sayhi(request: Request) -> Response:
    return PlainTextResponse("hi, " + request.path_params["name"])
Beispiel #15
0
 async def view(request: Request) -> Response:
     return PlainTextResponse(await request.body)
Beispiel #16
0
 async def app(scope, receive, send):
     if scope["path"] == "/":
         response = PlainTextResponse("hello, world")
     else:
         response = RedirectResponse("/")
     await response(scope, receive, send)
Beispiel #17
0
 async def request_validation_error(exc: RequestValidationError) -> HttpResponse:
     return PlainTextResponse(
         exc.json(), status_code=422, media_type="application/json"
     )
Beispiel #18
0
 async def root(request: Request) -> Response:
     return PlainTextResponse(request.get("root_path", ""))
Beispiel #19
0
 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)
Beispiel #20
0
 async def path(request: Request) -> Response:
     return PlainTextResponse(request["path"])