我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用eventlet.listen()。
def run(self, handler): from eventlet import wsgi, listen, patcher if not patcher.is_monkey_patched(os): msg = "Bottle requires eventlet.monkey_patch() (before import)" raise RuntimeError(msg) socket_args = {} for arg in ('backlog', 'family'): try: socket_args[arg] = self.options.pop(arg) except KeyError: pass address = (self.host, self.port) try: wsgi.server(listen(address, **socket_args), handler, log_output=(not self.quiet)) except TypeError: # Fallback, if we have old version of eventlet wsgi.server(listen(address), handler)
def main(): service.prepare_service("gapi", sys.argv) log.info('Completed configuration file parsing...') log.info('Completed logger initialization...') app = api.setup_app() log.info('Pecan app setup complete...') host, port = cfg.CONF.gapi.host, cfg.CONF.gapi.port log.info('Galaxia api server started in PID %s' % os.getpid()) log.info('Galaxia API is now serving on http://%(host)s:%(port)s' % dict( host=host, port=port)) print ('Galaxia API is now serving on http://%(host)s:%(port)s' % dict( host=host, port=port)) wsgi.server(eventlet.listen((host, port)), app, log=log)
def __init__(self, listen_info, handle=None, backlog=None, spawn='default', **ssl_args): assert backlog is None assert spawn == 'default' if ':' in listen_info[0]: self.server = eventlet.listen(listen_info, family=socket.AF_INET6) else: self.server = eventlet.listen(listen_info) if ssl_args: def wrap_and_handle(sock, addr): ssl_args.setdefault('server_side', True) handle(ssl.wrap_socket(sock, **ssl_args), addr) self.handle = wrap_and_handle else: self.handle = handle
def test_hub_exceptions(self): debug.hub_exceptions(True) server = eventlet.listen(('0.0.0.0', 0)) client = eventlet.connect(('127.0.0.1', server.getsockname()[1])) client_2, addr = server.accept() def hurl(s): s.recv(1) {}[1] # keyerror with capture_stderr() as fake: gt = eventlet.spawn(hurl, client_2) eventlet.sleep(0) client.send(b' ') eventlet.sleep(0) # allow the "hurl" greenlet to trigger the KeyError # not sure why the extra context switch is needed eventlet.sleep(0) self.assertRaises(KeyError, gt.wait) debug.hub_exceptions(False) # look for the KeyError exception in the traceback assert 'KeyError: 1' in fake.getvalue(), "Traceback not in:\n" + fake.getvalue()
def test_zero_timeout_and_back(self): listen = eventlet.listen(('', 0)) # Keep reference to server side of socket server = eventlet.spawn(listen.accept) client = eventlet.connect(listen.getsockname()) client.settimeout(0.05) # Now must raise socket.timeout self.assertRaises(socket.timeout, client.recv, 1) client.settimeout(0) # Now must raise socket.error with EAGAIN try: client.recv(1) assert False except socket.error as e: assert get_errno(e) == errno.EAGAIN client.settimeout(0.05) # Now socket.timeout again self.assertRaises(socket.timeout, client.recv, 1) server.wait()
def test_recv_type(): # https://github.com/eventlet/eventlet/issues/245 # socket recv returning multiple data types # For this test to work, client and server have to be in separate # processes or OS threads. Just running two greenthreads gives # false test pass. threading = eventlet.patcher.original('threading') addr = [] def server(): sock = eventlet.listen(('127.0.0.1', 0)) addr[:] = sock.getsockname() eventlet.sleep(0.2) server_thread = threading.Thread(target=server) server_thread.start() eventlet.sleep(0.1) sock = eventlet.connect(tuple(addr)) s = sock.recv(1) assert isinstance(s, bytes)
def test_recv_into_type(): # make sure `_recv_loop` returns the correct value when `recv_meth` is of # foo_into type (fills a buffer and returns number of bytes, not the data) # Using threads like `test_recv_type` above. threading = eventlet.patcher.original('threading') addr = [] def server(): sock = eventlet.listen(('127.0.0.1', 0)) addr[:] = sock.getsockname() eventlet.sleep(0.2) server_thread = threading.Thread(target=server) server_thread.start() eventlet.sleep(0.1) sock = eventlet.connect(tuple(addr)) buf = array.array('B', b' ') res = sock.recv_into(buf, 1) assert isinstance(res, int)
def test_ssl_unwrap(self): def serve(): sock, addr = listener.accept() self.assertEqual(sock.recv(6), b'before') sock_ssl = ssl.wrap_socket(sock, tests.private_key_file, tests.certificate_file, server_side=True) sock_ssl.do_handshake() self.assertEqual(sock_ssl.recv(6), b'during') sock2 = sock_ssl.unwrap() self.assertEqual(sock2.recv(5), b'after') sock2.close() listener = eventlet.listen(('127.0.0.1', 0)) server_coro = eventlet.spawn(serve) client = eventlet.connect(listener.getsockname()) client.sendall(b'before') client_ssl = ssl.wrap_socket(client) client_ssl.do_handshake() client_ssl.sendall(b'during') client2 = client_ssl.unwrap() client2.sendall(b'after') server_coro.wait()
def test_012_ssl_server(self): def wsgi_app(environ, start_response): start_response('200 OK', {}) return [environ['wsgi.input'].read()] certificate_file = os.path.join(os.path.dirname(__file__), 'test_server.crt') private_key_file = os.path.join(os.path.dirname(__file__), 'test_server.key') server_sock = eventlet.wrap_ssl(eventlet.listen(('localhost', 0)), certfile=certificate_file, keyfile=private_key_file, server_side=True) self.spawn_server(sock=server_sock, site=wsgi_app) sock = eventlet.connect(self.server_addr) sock = eventlet.wrap_ssl(sock) sock.write( b'POST /foo HTTP/1.1\r\nHost: localhost\r\n' b'Connection: close\r\nContent-length:3\r\n\r\nabc') result = recvall(sock) assert result.endswith(b'abc')
def test_013_empty_return(self): def wsgi_app(environ, start_response): start_response("200 OK", []) return [b""] certificate_file = os.path.join(os.path.dirname(__file__), 'test_server.crt') private_key_file = os.path.join(os.path.dirname(__file__), 'test_server.key') server_sock = eventlet.wrap_ssl(eventlet.listen(('localhost', 0)), certfile=certificate_file, keyfile=private_key_file, server_side=True) self.spawn_server(sock=server_sock, site=wsgi_app) sock = eventlet.connect(('localhost', server_sock.getsockname()[1])) sock = eventlet.wrap_ssl(sock) sock.write(b'GET /foo HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n') result = recvall(sock) assert result[-4:] == b'\r\n\r\n'
def test_ipv6(self): try: sock = eventlet.listen(('::1', 0), family=socket.AF_INET6) except (socket.gaierror, socket.error): # probably no ipv6 return log = six.StringIO() # first thing the server does is try to log the IP it's bound to def run_server(): try: wsgi.server(sock=sock, log=log, site=Site()) except ValueError: log.write(b'broken') self.spawn_thread(run_server) logval = log.getvalue() while not logval: eventlet.sleep(0.0) logval = log.getvalue() if 'broked' in logval: self.fail('WSGI server raised exception with ipv6 socket')
def test_client_disconnect(self): """Issue #95 Server must handle disconnect from client in the middle of response """ def long_response(environ, start_response): start_response('200 OK', [('Content-Length', '9876')]) yield b'a' * 9876 server_sock = eventlet.listen(('localhost', 0)) self.server_addr = server_sock.getsockname() server = wsgi.Server(server_sock, server_sock.getsockname(), long_response, log=self.logfile) def make_request(): sock = eventlet.connect(server_sock.getsockname()) sock.send(b'GET / HTTP/1.1\r\nHost: localhost\r\n\r\n') sock.close() request_thread = eventlet.spawn(make_request) client_sock, addr = server_sock.accept() # Next line must not raise IOError -32 Broken pipe server.process_request([addr, client_sock, wsgi.STATE_IDLE]) request_thread.wait() server_sock.close()
def test_001_trampoline_timeout(self): server_sock = eventlet.listen(('127.0.0.1', 0)) bound_port = server_sock.getsockname()[1] def server(sock): client, addr = sock.accept() eventlet.sleep(0.1) server_evt = eventlet.spawn(server, server_sock) eventlet.sleep(0) try: desc = eventlet.connect(('127.0.0.1', bound_port)) hubs.trampoline(desc, read=True, write=False, timeout=0.001) except eventlet.Timeout: pass # test passed else: assert False, "Didn't timeout" server_evt.wait() check_hub()
def test_concurrency(self): evt = eventlet.Event() def waiter(sock, addr): sock.sendall(b'hi') evt.wait() l = eventlet.listen(('localhost', 0)) eventlet.spawn(eventlet.serve, l, waiter, 5) def test_client(): c = eventlet.connect(('localhost', l.getsockname()[1])) # verify the client is connected by getting data self.assertEqual(b'hi', c.recv(2)) return c [test_client() for i in range(5)] # very next client should not get anything x = eventlet.with_timeout( 0.01, test_client, timeout_value="timed out") self.assertEqual(x, "timed out")
def run(self, handler): from meinheld import server server.listen((self.host, self.port)) server.run(handler)
def run(self, handler): # pragma: no cover import tornado.wsgi, tornado.httpserver, tornado.ioloop container = tornado.wsgi.WSGIContainer(handler) server = tornado.httpserver.HTTPServer(container) server.listen(port=self.port, address=self.host) tornado.ioloop.IOLoop.instance().start()
def route(self, path=None, method='GET', callback=None, name=None, apply=None, skip=None, **config): """ A decorator to bind a function to a request URL. Example:: @app.route('/hello/:name') def hello(name): return 'Hello %s' % name The ``:name`` part is a wildcard. See :class:`Router` for syntax details. :param path: Request path or a list of paths to listen to. If no path is specified, it is automatically generated from the signature of the function. :param method: HTTP method (`GET`, `POST`, `PUT`, ...) or a list of methods to listen to. (default: `GET`) :param callback: An optional shortcut to avoid the decorator syntax. ``route(..., callback=func)`` equals ``route(...)(func)`` :param name: The name for this route. (default: None) :param apply: A decorator or plugin or a list of plugins. These are applied to the route callback in addition to installed plugins. :param skip: A list of plugins, plugin classes or names. Matching plugins are not installed to this route. ``True`` skips all. Any additional keyword arguments are stored as route-specific configuration and passed to plugins (see :meth:`Plugin.apply`). """ if callable(path): path, callback = None, path plugins = makelist(apply) skiplist = makelist(skip) def decorator(callback): # TODO: Documentation and tests if isinstance(callback, basestring): callback = load(callback) for rule in makelist(path) or yieldroutes(callback): for verb in makelist(method): verb = verb.upper() route = Route(self, rule, verb, callback, name=name, plugins=plugins, skiplist=skiplist, **config) self.add_route(route) return callback return decorator(callback) if callback else decorator
def run(self, handler): # pragma: no cover import tornado.wsgi, tornado.httpserver, tornado.ioloop container = tornado.wsgi.WSGIContainer(handler) server = tornado.httpserver.HTTPServer(container) server.listen(port=self.port,address=self.host) tornado.ioloop.IOLoop.instance().start()
def run(self, handler): from eventlet import wsgi, listen try: wsgi.server(listen((self.host, self.port)), handler, log_output=(not self.quiet)) except TypeError: # Fallback, if we have old version of eventlet wsgi.server(listen((self.host, self.port)), handler)
def route(self, path=None, method='GET', callback=None, name=None, apply=None, skip=None, **config): """ A decorator to bind a function to a request URL. Example:: @app.route('/hello/:name') def hello(name): return 'Hello %s' % name The ``:name`` part is a wildcard. See :class:`Router` for syntax details. :param path: Request path or a list of paths to listen to. If no path is specified, it is automatically generated from the signature of the function. :param method: HTTP method (`GET`, `POST`, `PUT`, ...) or a list of methods to listen to. (default: `GET`) :param callback: An optional shortcut to avoid the decorator syntax. ``route(..., callback=func)`` equals ``route(...)(func)`` :param name: The name for this route. (default: None) :param apply: A decorator or plugin or a list of plugins. These are applied to the route callback in addition to installed plugins. :param skip: A list of plugins, plugin classes or names. Matching plugins are not installed to this route. ``True`` skips all. Any additional keyword arguments are stored as route-specific configuration and passed to plugins (see :meth:`Plugin.apply`). """ if callable(path): path, callback = None, path plugins = makelist(apply) skiplist = makelist(skip) def decorator(callback): if isinstance(callback, basestring): callback = load(callback) for rule in makelist(path) or yieldroutes(callback): for verb in makelist(method): verb = verb.upper() route = Route(self, rule, verb, callback, name=name, plugins=plugins, skiplist=skiplist, **config) self.add_route(route) return callback return decorator(callback) if callback else decorator
def tornado(app, address, **options): import tornado.wsgi import tornado.httpserver import tornado.ioloop container = tornado.wsgi.WSGIContainer(app) server = tornado.httpserver.HTTPServer(container) server.listen(address=address[0], port=address[1]) tornado.ioloop.IOLoop.instance().start()
def eventlet(app, address, **options): from eventlet import wsgi, listen wsgi.server(listen(address), app)
def motor(app, address, **options): #https://github.com/rpedroso/motor import motor app = motor.WSGIContainer(app) http_server = motor.HTTPServer(app) http_server.listen(address=address[0], port=address[1]) #http_server.start(2) motor.IOLoop.instance().start()
def _start_listening_blocking(self): # deploy as an eventlet WSGI server listener = eventlet.listen((self.host, self.port)) self.server = wsgi.server(listener, self.app, log_output=False, debug=False)