def server(): s = WebSocketServer(('0.0.0.0', 8001), Resource(OrderedDict([('/', TestApplication)]))) s.start() thread = Greenlet.spawn(s.serve_forever) yield s s.stop() thread.kill()
def server(): s = WebSocketServer( ('0.0.0.0', 8001), Resource(OrderedDict([('/', WsApplication)])) ) s.start() thread = Greenlet.spawn(s.serve_forever) yield s s.stop() thread.kill()
def main(): """ ======================================== Codigo que no se para que sirve ======================================== """ opt = process_command_line() zmq_ctx = zmq.Context() # Pasandole el contexto del mensajero, y el nombre de la camara came_0 = CameraLink(zmq_ctx, 'cam0') came_0.connect(opt.camera_server_address) # Si hay mas camaras, se deben seguir asociando con este formato camaras = {'cam0': came_0} # Actualizando el objeto global objects.update(camaras) objects['last-image'] = None # No existe el metodo motor_debug # motor_execution.debug = opt.motor_debug motor_execution.restart() gevent.spawn(motor_execution.uart_readout_loop) # Iniciando el SweepControllet controlador = SweepController(camaras, motor_execution, sweep_status_broadcast, debug=True) objects['sweep-controller'] = controlador # configurando el broadcast de la camara came_0_config_broadcast = functools.partial(websockets_broadcast, identity=came_0.name, Kind='cfg') # devolviendo el estado del broadcast came_0_status_broadcast = functools.partial(camera_status_callback, identity=came_0.name) # Inicializando la camara came_0.start(came_0_config_broadcast, came_0_status_broadcast) resources = OrderedDict() # Agregando 2 pares al objeto OrderedDict # Equivale a .append resources['^/websocket'] = WSApplication resources['^/.*'] = app # Server de websocket server = WebSocketServer(('0.0.0.0', opt.port), Resource(resources)) # Funcion que apaga el motor def shutdown(): for motor in motor_api.motor_address.keys(): motor_execution.set_hold_force(motor, False) gevent.sleep(0.01) motor_execution.set_axes_enabled(False) server.stop() zmq_ctx.destroy() sys.exit() gevent.signal(signal.SIGINT, shutdown) gevent.signal(signal.SIGTERM, shutdown) # Procesando una o varias solicitudes server.serve_forever()
class APIServer(): _api_prefix = '/api/1' def __init__( self, rest_api: RestAPI, ws_notifier: RotkiNotifier, cors_domain_list: List[str] = None, ) -> None: flask_app = Flask(__name__) if cors_domain_list: CORS(flask_app, origins=cors_domain_list) blueprint = create_blueprint() flask_api_context = Api(blueprint, prefix=self._api_prefix) setup_urls( flask_api_context=flask_api_context, rest_api=rest_api, urls=URLS_V1, ) self.rest_api = rest_api self.rotki_notifier = ws_notifier self.flask_app = flask_app self.blueprint = blueprint self.wsgiserver: Optional[WSGIServer] = None self.flask_app.register_blueprint(self.blueprint) self.ws_server: Optional[WebSocketServer] = None self.flask_app.errorhandler(HTTPStatus.NOT_FOUND)( endpoint_not_found) # type: ignore self.flask_app.register_error_handler( Exception, self.unhandled_exception) # type: ignore @staticmethod def unhandled_exception(exception: Exception) -> Response: """ Flask.errorhandler when an exception wasn't correctly handled """ log.critical( 'Unhandled exception when processing endpoint request', exc_info=True, exception=str(exception), ) return api_response(wrap_in_fail_result(str(exception)), HTTPStatus.INTERNAL_SERVER_ERROR) def run(self, host: str = '127.0.0.1', port: int = 5042, **kwargs: Any) -> None: """This is only used for the data faker and not used in production""" self.flask_app.run(host=host, port=port, **kwargs) def start( self, host: str = '127.0.0.1', rest_port: int = 5042, websockets_port: int = 5043, ) -> None: """This is used to start the API server in production""" wsgi_logger = logging.getLogger(__name__ + '.pywsgi') self.wsgiserver = WSGIServer( listener=(host, rest_port), application=self.flask_app, log=wsgi_logger, error_log=wsgi_logger, ) msg = f'rotki REST API server is running at: {host}:{rest_port}' print(msg) log.info(msg) self.wsgiserver.start() self.ws_server = WebSocketServer( listener=(host, websockets_port), application=WebsocketResource([ ('^/', RotkiWSApp), ]), debug=False, environ={'rotki_notifier': self.rotki_notifier}, ) msg = f'rotki Websockets API server is running at: {host}:{websockets_port}' print(msg) log.info(msg) self.ws_server.start() def stop(self, timeout: int = 5) -> None: """Stops the API server. If handlers are running after timeout they are killed""" if self.wsgiserver is not None: self.wsgiserver.stop(timeout) self.wsgiserver = None if self.ws_server is not None: self.ws_server.stop(timeout) self.wsgiserver = None self.rest_api.stop()