def app(environ, start_response): request = Request(environ) if request.accepts("application/json"): response = JSONResponse({"data": data}) else: response = PlainTextResponse(data) return response(environ, start_response)
def app(environ, start_response): request = Request(environ) body = b"" for chunk in request.stream(): body += chunk response = PlainTextResponse(body) return response(environ, start_response)
def test_hosts(): with httpx.Client( app=Hosts( ("testServer", PlainTextResponse("testServer")), (".*", PlainTextResponse("default host")), ), base_url="http://testServer/", ) as client: assert client.get("/", headers={ "host": "testServer" }).text == "testServer" assert client.get("/", headers={ "host": "hhhhhhh" }).text == "default host" assert client.get("/", headers={ "host": "qwe\ndsf" }).text == "Invalid host"
def test_router(): @request_response def path(request: Request) -> Response: return JSONResponse(request.path_params) @request_response def redirect(request: Request) -> Response: return RedirectResponse("/cat") router = Router( ("/", PlainTextResponse("homepage")), ("/redirect", redirect), ("/{path}", path), ) with httpx.Client(app=router, base_url="http://testServer/") as client: assert client.get("/").text == "homepage" assert client.get("/baize").json() == {"path": "baize"} assert client.get("/baize/").status_code == 404 assert client.get("/redirect").headers["location"] == "/cat"
def echo(request: Request) -> Response: return PlainTextResponse(request.body)
def sayhi(request: Request) -> Response: return PlainTextResponse("hi, " + request.path_params["name"])
Response]) -> Response: start_time = time.time() response = next_call(request) end_time = time.time() response.headers["x-time"] = str(round((end_time - start_time) * 1000)) return response @request_response @timer def sayhi(request: Request) -> Response: return PlainTextResponse("hi, " + request.path_params["name"]) @request_response @timer def echo(request: Request) -> Response: return PlainTextResponse(request.body) application = Router( ("/", PlainTextResponse("homepage")), ("/echo", echo), ("/sayhi/{name}", sayhi), ) if __name__ == "__main__": import uvicorn uvicorn.run(application, interface="wsgi", port=8000)
def user(request): return PlainTextResponse(request.path_params["user_id"])
def homepage(request): return PlainTextResponse("")
def userinfo(request): return PlainTextResponse("")
def app(environ, start_response): request = Request(environ) response = PlainTextResponse(request.method + " " + str(request.url)) return response(environ, start_response)
def path(request: Request) -> Response: return PlainTextResponse(request.get("PATH_INFO", ""))
def root(request: Request) -> Response: return PlainTextResponse(request.get("SCRIPT_NAME", ""))
def app(environ, start_response): if environ["PATH_INFO"] == "/": response = PlainTextResponse("hello, world") else: response = RedirectResponse("/") return response(environ, start_response)