def run(app, **kwargs): config = Config(app, **kwargs) server = Server(config=config) if (config.reload or config.workers > 1) and not isinstance(app, str): logger = logging.getLogger("uvicorn.error") logger.warning( "You must pass the application as an import string to enable 'reload' or " "'workers'.") sys.exit(1) if config.should_reload: sock = config.bind_socket() use_watchman = config.reload_with_watchman and WatchmanReload.available( ) watchman_unavailable = (config.reload_with_watchman and not WatchmanReload.available()) if watchman_unavailable: logger = logging.getLogger("uvicorn.error") logger.warning( "Watchman service is unavailable fallback to other reloader.") Reloader = WatchmanReload if use_watchman else ChangeReload supervisor = Reloader(config, target=server.run, sockets=[sock]) supervisor.run() elif config.workers > 1: sock = config.bind_socket() supervisor = Multiprocess(config, target=server.run, sockets=[sock]) supervisor.run() else: server.run()
def _run_uvicorn_server(server: UvicornServer) -> None: # The following was copied from the uvicorn source with minimal modification. We # shouldn't need to do this, but unfortunately there's no easy way to gain access to # the server instance so you can stop it. # BUG: https://github.com/encode/uvicorn/issues/742 config = server.config if (config.reload or config.workers > 1) and not isinstance( server.config.app, str): # pragma: no cover logger = logging.getLogger("uvicorn.error") logger.warning( "You must pass the application as an import string to enable 'reload' or " "'workers'.") sys.exit(1) if config.should_reload: # pragma: no cover sock = config.bind_socket() supervisor = ChangeReload(config, target=server.run, sockets=[sock]) supervisor.run() elif config.workers > 1: # pragma: no cover sock = config.bind_socket() supervisor = Multiprocess(config, target=server.run, sockets=[sock]) supervisor.run() else: import asyncio asyncio.set_event_loop(asyncio.new_event_loop()) server.run()
def run(app: typing.Union[ASGIApplication, str], **kwargs: typing.Any) -> None: app_dir = kwargs.pop("app_dir", None) if app_dir is not None: sys.path.insert(0, app_dir) config = Config(app, **kwargs) server = Server(config=config) if (config.reload or config.workers > 1) and not isinstance(app, str): logger = logging.getLogger("uvicorn.error") logger.warning( "You must pass the application as an import string to enable 'reload' or " "'workers'.") sys.exit(1) if config.should_reload: sock = config.bind_socket() ChangeReload(config, target=server.run, sockets=[sock]).run() elif config.workers > 1: sock = config.bind_socket() Multiprocess(config, target=server.run, sockets=[sock]).run() else: server.run() if config.uds: os.remove(config.uds) # pragma: py-win32 if not server.started and not config.should_reload and config.workers == 1: sys.exit(STARTUP_FAILURE)
class ApiServer(Thread): camera_manager = None server = None def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, camera_manager=None): super(ApiServer,self).__init__(group=group, target=target, name=name) self.camera_manager = camera_manager def run(self): log("[api] Starting service") try: app = FastAPI(exception_handlers={APIException: http_exception_handler}) app.camera_manager = self.camera_manager protected = Depends(HTTPHeaderAuthentication()) app.include_router(camera.router, prefix="/api", dependencies=[protected]) app.include_router(camera.public_router, prefix="/api") app.include_router(clips.router, prefix="/api", dependencies=[protected]) app.include_router(clips.public_router, prefix="/api") app.include_router(auth.router, prefix="/api") app.include_router(system.router, prefix="/api") app.include_router(timelapse.router, prefix="/api", dependencies=[protected]) app.include_router(timelapse.public_router, prefix="/api") app.mount("/", StaticFiles(directory="../web/dist", html=True), name="public") app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) config = Config(app, host=os.environ["API_SERVER_HOST"], port=int(os.environ["API_SERVER_PORT"])) self.server = Server(config=config) if config.should_reload: sock = config.bind_socket() supervisor = ChangeReload(config, target=self.server.run, sockets=[sock]) supervisor.run() elif config.workers > 1: sock = config.bind_socket() supervisor = Multiprocess(config, target=self.server.run, sockets=[sock]) supervisor.run() else: self.server.run() except KeyboardInterrupt: pass def stop(self): self.server.handle_exit(None, None) self.join()
def run(app: typing.Union[ASGIApplication, str], **kwargs: typing.Any) -> None: config = Config(app, **kwargs) server = Server(config=config) if (config.reload or config.workers > 1) and not isinstance(app, str): logger = logging.getLogger("uvicorn.error") logger.warning( "You must pass the application as an import string to enable 'reload' or " "'workers'.") sys.exit(1) if config.should_reload: sock = config.bind_socket() ChangeReload(config, target=server.run, sockets=[sock]).run() elif config.workers > 1: sock = config.bind_socket() Multiprocess(config, target=server.run, sockets=[sock]).run() else: server.run()
class Server(threading.Thread): def __init__(self, port, host='localhost', **kwargs): self.port = port self.host = host self.kwargs = kwargs self.started = threading.Event() self.stopped = threading.Event() super().__init__(name="fastapi-thread") self.setDaemon(True) def set_datasets(self, dfs): global datasets dfs = {df.name: df for df in dfs} update_service(dfs) def run(self): self.mainloop() def serve_threaded(self): logger.debug("start thread") self.start() logger.debug("wait for thread to run") self.started.wait() logger.debug("make tornado io loop the main thread's current") def wait_until_serving(self): for n in range(10): url = f'http://{self.host}:{self.port}/' try: response = requests.get(url) except requests.exceptions.ConnectionError: pass else: if response.status_code == 200: return time.sleep(0.05) else: raise RuntimeError(f'Server at {url} does not seem to be running') def mainloop(self): logger.info("serving at http://%s:%d" % (self.host, self.port)) from uvicorn.config import Config from uvicorn.server import Server # uvloop will trigger a: RuntimeError: There is no current event loop in thread 'fastapi-thread' config = Config(app, host=self.host, port=self.port, **self.kwargs, loop='asyncio') self.server = Server(config=config) self.started.set() try: self.server.run() except: logger.exception("Oops, server stopped unexpectedly") finally: self.stopped.set() def stop_serving(self): logger.debug("stopping server") self.server.should_exit = True if self.stopped.wait(1) is not None: logger.error('stopping server failed') logger.debug("stopped server")
def run( app: typing.Union[ASGIApplication, str], *, host: str = "127.0.0.1", port: int = 8000, uds: typing.Optional[str] = None, fd: typing.Optional[int] = None, loop: LoopSetupType = "auto", http: HTTPProtocolType = "auto", ws: WSProtocolType = "auto", ws_max_size: int = 16777216, ws_ping_interval: float = 20.0, ws_ping_timeout: float = 20.0, ws_per_message_deflate: bool = True, lifespan: LifespanType = "auto", interface: InterfaceType = "auto", debug: bool = False, reload: bool = False, reload_dirs: typing.Optional[typing.List[str]] = None, reload_includes: typing.Optional[typing.List[str]] = None, reload_excludes: typing.Optional[typing.List[str]] = None, reload_delay: float = 0.25, workers: typing.Optional[int] = None, env_file: typing.Optional[str] = None, log_config: typing.Optional[typing.Union[dict, str]] = None, log_level: typing.Optional[str] = None, access_log: bool = True, proxy_headers: bool = True, server_header: bool = True, date_header: bool = True, forwarded_allow_ips: typing.Optional[str] = None, root_path: str = "", limit_concurrency: typing.Optional[int] = None, backlog: int = 2048, limit_max_requests: typing.Optional[int] = None, timeout_keep_alive: int = 5, ssl_keyfile: typing.Optional[str] = None, ssl_certfile: typing.Optional[str] = None, ssl_keyfile_password: typing.Optional[str] = None, ssl_version: int = int(SSL_PROTOCOL_VERSION), ssl_cert_reqs: int = int(ssl.CERT_NONE), ssl_ca_certs: typing.Optional[str] = None, ssl_ciphers: str = "TLSv1", headers: typing.Optional[typing.List[typing.Tuple[str, str]]] = None, use_colors: typing.Optional[bool] = None, app_dir: typing.Optional[str] = None, factory: bool = False, ) -> None: if app_dir is not None: sys.path.insert(0, app_dir) config = Config( app, host=host, port=port, uds=uds, fd=fd, loop=loop, http=http, ws=ws, ws_max_size=ws_max_size, ws_ping_interval=ws_ping_interval, ws_ping_timeout=ws_ping_timeout, ws_per_message_deflate=ws_per_message_deflate, lifespan=lifespan, interface=interface, debug=debug, reload=reload, reload_dirs=reload_dirs, reload_includes=reload_includes, reload_excludes=reload_excludes, reload_delay=reload_delay, workers=workers, env_file=env_file, log_config=log_config, log_level=log_level, access_log=access_log, proxy_headers=proxy_headers, server_header=server_header, date_header=date_header, 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_keyfile_password=ssl_keyfile_password, ssl_version=ssl_version, ssl_cert_reqs=ssl_cert_reqs, ssl_ca_certs=ssl_ca_certs, ssl_ciphers=ssl_ciphers, headers=headers, use_colors=use_colors, factory=factory, ) server = Server(config=config) if (config.reload or config.workers > 1) and not isinstance(app, str): logger = logging.getLogger("uvicorn.error") logger.warning( "You must pass the application as an import string to enable 'reload' or " "'workers'.") sys.exit(1) if config.should_reload: sock = config.bind_socket() ChangeReload(config, target=server.run, sockets=[sock]).run() elif config.workers > 1: sock = config.bind_socket() Multiprocess(config, target=server.run, sockets=[sock]).run() else: server.run() if config.uds: os.remove(config.uds) # pragma: py-win32 if not server.started and not config.should_reload and config.workers == 1: sys.exit(STARTUP_FAILURE)