class LibraryServer(TestServer): def __init__(self, library_path, libraries=(), plugins=(), **kwargs): Thread.__init__(self, name='ServerMain') from calibre.srv.opts import Options from calibre.srv.loop import ServerLoop from calibre.srv.handler import Handler from calibre.srv.http_response import create_http_handler self.setup_defaults(kwargs) opts = Options(**kwargs) self.libraries = libraries or (library_path, ) self.handler = Handler(self.libraries, opts, testing=True) self.loop = ServerLoop( create_http_handler(self.handler.dispatch), opts=opts, plugins=plugins, log=ServerLog(level=ServerLog.DEBUG), ) self.log = self.loop.log self.handler.set_log(self.log) def __exit__(self, *args): try: self.loop.stop() except Exception as e: self.log.error('Failed to stop server with error:', e) self.handler.close() self.join(self.loop.opts.shutdown_timeout) self.loop.close_control_connection()
class TestServer(Thread): daemon = True def __init__(self, handler, plugins=(), **kwargs): Thread.__init__(self, name='ServerMain') from calibre.srv.opts import Options from calibre.srv.loop import ServerLoop from calibre.srv.http_response import create_http_handler self.setup_defaults(kwargs) self.loop = ServerLoop( create_http_handler(handler), opts=Options(**kwargs), plugins=plugins, log=ServerLog(level=ServerLog.DEBUG), ) self.log = self.loop.log def setup_defaults(self, kwargs): kwargs['shutdown_timeout'] = kwargs.get('shutdown_timeout', 0.1) kwargs['listen_on'] = kwargs.get('listen_on', 'localhost') kwargs['port'] = kwargs.get('port', 0) kwargs['userdb'] = kwargs.get('userdb', ':memory:') def run(self): try: self.loop.serve_forever() except KeyboardInterrupt: pass def __enter__(self): self.start() while not self.loop.ready and self.is_alive(): time.sleep(0.01) self.address = self.loop.bound_address[:2] return self def __exit__(self, *args): try: self.loop.stop() except Exception as e: self.log.error('Failed to stop server with error:', e) self.join(self.loop.opts.shutdown_timeout) self.loop.close_control_connection() def connect(self, timeout=None, interface=None): if timeout is None: timeout = self.loop.opts.timeout if interface is None: interface = self.address[0] ans = http_client.HTTPConnection(interface, self.address[1], timeout=timeout) ans.connect() return ans def change_handler(self, handler): from calibre.srv.http_response import create_http_handler self.loop.handler = create_http_handler(handler)