def test_run_invalid_app_config_combination(caplog: pytest.LogCaptureFixture) -> None: with pytest.raises(SystemExit) as exit_exception: run(app, reload=True) assert exit_exception.value.code == 1 assert caplog.records[-1].name == "uvicorn.error" assert caplog.records[-1].levelno == WARNING assert caplog.records[-1].message == ( "You must pass the application as an import string to enable " "'reload' or 'workers'." )
def test_run_startup_failure(caplog: pytest.LogCaptureFixture) -> None: async def app(scope, receive, send): assert scope["type"] == "lifespan" message = await receive() if message["type"] == "lifespan.startup": raise RuntimeError("Startup failed") with pytest.raises(SystemExit) as exit_exception: run(app, lifespan="on") assert exit_exception.value.code == 3
def start_service(listen_address: Optional[str] = None, reload: Optional[bool] = False): # pragma: no cover from uvicorn.main import run setup_logging() if listen_address is None: listen_address = "127.0.0.1:7890" host, port = listen_address.split(":") port = int(port) run(app="wetterdienst.ui.restapi:app", host=host, port=port, reload=reload)
def asgi() -> None: """uvicorn ASGI dev server""" load_init_function_from_entry_points() argv: List[str] = copy(sys.argv) Configuration.load("uvicorn") sys.argv = argv configuration_post_load() BlokManager.load() kwargs = { "app": create_app(preload_database(loadwithoutmigration=False)), "host": Configuration.get("host"), "port": Configuration.get("port"), # "uds": uds, # "fd": fd, # "loop": loop, # "http": http, # "ws": ws, # "lifespan": lifespan, # "env_file": env_file, # "log_config": LOGGING_CONFIG if log_config is None else log_config, # "log_level": log_level, # "access_log": access_log, # "interface": interface, # "debug": debug, # "reload": reload, # "reload_dirs": reload_dirs if reload_dirs else None, # "workers": workers, # "proxy_headers": proxy_headers, # "forwarded_allow_ips": forwarded_allow_ips, # "root_path": root_path, # "limit_concurrency": limit_concurrency, # "backlog": backlog, # "limit_max_requests": limit_max_requests, # "timeout_keep_alive": timeout_keep_alive, # "ssl_keyfile": ssl_keyfile, # "ssl_certfile": ssl_certfile, # "ssl_version": ssl_version, # "ssl_cert_reqs": ssl_cert_reqs, # "ssl_ca_certs": ssl_ca_certs, # "ssl_ciphers": ssl_ciphers, # "headers": list([header.split(":") for header in headers]), # "use_colors": use_colors, } run(**kwargs)
def run(): """ Entry-point to have the ability to perform some application start logic. """ c = configure(app) from uvicorn.main import run return run('pansen.castlabs.main:app', host=c.HTTP_HOST, port=c.HTTP_PORT, log_config=log_config())
from fastapi import FastAPI from uvicorn.main import run app = FastAPI() @app.post("/index") async def req(): return {"code": 0, "msg": "Hello Word"} @app.get("/in") async def req(): return {"code": 1, "msg": "Test Word"} if __name__ == '__main__': run(app, host="0.0.0.0")
@app.route("/", methods=["GET"]) async def list_all(_: Request) -> JSONResponse: users = await Users.all() return JSONResponse({"users": [str(user) for user in users]}) @app.route("/user", methods=["POST"]) async def add_user(request: Request) -> JSONResponse: try: payload = await request.json() username = payload["username"] except JSONDecodeError: raise HTTPException(status_code=HTTP_400_BAD_REQUEST, detail="cannot parse request body") except KeyError: raise HTTPException(status_code=HTTP_400_BAD_REQUEST, detail="username is required") user = await Users.create(username=username) return JSONResponse({"user": str(user)}, status_code=HTTP_201_CREATED) register_tortoise(app, db_url="sqlite://:memory:", modules={"models": ["models"]}, generate_schemas=True) if __name__ == "__main__": run(app)
def start_service(listen_address): # pragma: no cover host, port = listen_address.split(":") port = int(port) from uvicorn.main import run run(app="wetterdienst.service:app", host=host, port=port, reload=True)
def runserver(): run( settings.ASGI_APP, debug=settings.DEBUG, reload=True, )