def handle(self, *args, **options): port = options["port"] set_perms = options["set_perms"] verbosity = "-v 1" if DEBUG else "-v 0" # Run any preconfiguration tasks if not options["disable_preconfig"]: preconfig_args = [ "preconfig_conreq", options["uid"], options["gid"], ] if not set_perms: preconfig_args.append("--no-perms") call_command(*preconfig_args) # Execute tests to ensure Conreq is healthy before starting if not options["skip_checks"]: call_command("test", "--noinput", "--parallel", "--failfast") # Perform any debug related clean-up if DEBUG: print("Conreq is in DEBUG mode.") print("Clearing cache...") cache.clear() print("Removing stale background tasks...") self.reset_huey_db() # Migrate the database call_command("migrate", "--noinput", verbosity) if not DEBUG: # Collect static files call_command("collectstatic", "--link", "--clear", "--noinput", verbosity) call_command("compress", "--force", verbosity) # Run background task management proc = Process(target=self.start_huey, daemon=True) proc.start() # Run the production webserver if not DEBUG: config = HypercornConfig() config.bind = f"0.0.0.0:{port}" config.websocket_ping_interval = 20 config.workers = 3 config.application_path = "conreq.asgi:application" config.accesslog = ACCESS_LOG_FILE # Additonal webserver configuration if os.path.exists(HYPERCORN_TOML): config.from_toml(HYPERCORN_TOML) # Run the webserver run_hypercorn(config) # Run the development webserver if DEBUG: call_command("runserver", f"0.0.0.0:{port}")
async def __start_webserver(self): class SinglePageApplication(StaticFiles): async def get_response(self, path, scope): response = await super().get_response(path, scope) if response.status_code == 404: response = await super().get_response('.', scope) return response app = FastAPI() server_config = Config() server_config.accesslog = '-' server_config.behind_proxy = config['behind_proxy'] server_config.keyfile = config['keyfile'] server_config.certfile = config['certfile'] if config['production']: server_config.bind = ['0.0.0.0:8000', '[::]:8000'] api = FastAPI() api.include_router(router) app.mount('/api', api) if not config['production'] and config['cors_allow_origin']: app.add_middleware( CORSMiddleware, allow_origins=config['cors_allow_origin'], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) if config['frontend_path'] is not None: app.mount( '/', app=SinglePageApplication(directory=config['frontend_path'], html=True), ) await serve(app, server_config)
def quart_run(self): # looked at the hypercorn and quart Python project to figure out # how to start the application separately, without going through # the Quart.app.run APIs config = HyperConfig() config.debug = self.debug config.access_log_format = "%(h)s %(r)s %(s)s %(b)s %(D)s" config.accesslog = self.LOGGER config.bind = [ "{host}:{port}".format(**{ 'host': self._App_host, 'port': self._App_port }) ] config.certfile = self._App_server_crt config.keyfile = self._App_server_key config.errorlog = config.accesslog config.use_reloader = True scheme = "https" if config.ssl_enabled else "http" self.LOGGER.info("Running on {}://{} (CTRL + C to quit)".format( scheme, config.bind[0])) loop = None #asyncio.get_event_loop() if loop is not None: loop.set_debug(debug or False) loop.run_until_complete(serve(self, config)) else: asyncio.run(serve(self, config), debug=config.debug)
def run(options, connection_uri): from app.main import app click.secho("Checking configuration ...", fg="yellow") try: urlparse(connection_uri)._replace( path="/{{cookiecutter.project_name}}").geturl() assert (hasattr(options, 'production')) except Exception as e: click.echo(e) click.secho("Failed to validate database URI and password", fg="red") click.secho("Starting server ...", fg="yellow") config = Config() config.bind = ["0.0.0.0:8080"] config.errorlog = logger config.accesslog = logger if options.production: config.loglevel = "DEBUG" else: config.loglevel = "INFO" if 'uvloop' in sys.modules: asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(serve(app, config)) else: asyncio.run(serve(app, config))
async def startQuart(si): print(f"{si['serviceName']}({si['instanceID']})(v{si['serviceVersion']}) running at {si['serviceIP']}:{si['servicePort']}") config = Config() config.bind = [f"{si['serviceIP']}:{si['servicePort']}"] # config.bind = [f"0.0.0.0:{si['servicePort']}"] config.access_log_format = '%(h)s %(r)s %(s)s %(b)s %(D)s' config.accesslog = create_serving_logger() config.errorlog = config.accesslog loop = asyncio.get_event_loop() await loop.create_task(serve(app, config))
def start_app(self, debug): ssl_context = None self.logger.debug("Preparing to start rest-service") if self.get_use_ssl() and self.get_key_pem() is not None and \ self.get_cert_pem() is not None: self.logger.debug( "Preparing ssl_context with cert:{} and key:{}".format( self.get_cert_pem(), self.get_key_pem())) ssl_context = (self.get_cert_pem(), self.get_key_pem()) self.logger.info("Starting the application {}:{} using ssl? {}".format( self.get_listening_host(), self.get_listening_port(), ssl_context is None)) # looked at the hypercorn and quart Python project to figure out # how to start the application separately, without going through # the Quart.app.run APIs self.app.debug = debug config = HyperConfig() config.debug = debug config.access_log_format = "%(h)s %(r)s %(s)s %(b)s %(D)s" config.accesslog = self.logger.logger config.bind = [ "{host}:{port}".format( **{ 'host': self.get_listening_host(), 'port': self.get_listening_port() }) ] config.certfile = self.get_cert_pem() if self.get_use_ssl() else None config.keyfile = self.get_key_pem() if self.get_use_ssl() else None config.errorlog = config.accesslog config.use_reloader = True scheme = "https" if config.ssl_enabled else "http" self.logger.info("Running on {}://{} (CTRL + C to quit)".format( scheme, config.bind[0])) loop = asyncio.get_event_loop() if loop is not None: loop.set_debug(debug or False) loop.run_until_complete(serve(self.app, config)) else: asyncio.run(serve(self.app, config), debug=config.debug)
def test_access_logger_init( target: Union[logging.Logger, str, None], expected_name: Optional[str], expected_handler_type: Optional[Type[logging.Handler]], ) -> None: config = Config() config.accesslog = target config.access_log_format = "%h" logger = Logger(config) assert logger.access_log_format == "%h" assert logger.getEffectiveLevel() == logging.INFO if expected_name is None: assert logger.access_logger.handlers == [] else: assert logger.access_logger.name == expected_name if expected_handler_type is None: assert logger.access_logger.handlers == [] else: assert isinstance(logger.access_logger.handlers[0], expected_handler_type)
sys.path.append('../vogdb') sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from vogdb import main import signal # Configuration config = Config() config.bind = ["localhost:8000"] # here we add our domain config.use_reloader = True config.graceful_timeout = 60.0 config.h11_max_incomplete_size = 16384 config.h2_max_concurrent_streams = 100 config.h2_max_header_list_size = 65536 config.h2_max_inbound_frame_size = 16384 config.access_log_format = '%(h)s %(l)s %(l)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"' config.accesslog = "-" #path to log file config.errorlog = "-" #path to error log file config.statsd_host = "localhost:8000" #config.server_names = ["test"] # uncomment when we have an actual domain and SSL certificates # config.ca_certs = <path/to/cert.pem> # config.keyfile = <path/to/key.pem> # config.insecure_bind = ["domain:80"] asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) shutdown_event = asyncio.Event() def _signal_handler(*_: Any) -> None: shutdown_event.set()