本文整理汇总了Python中tornado.httpserver.HTTPServer.stop方法的典型用法代码示例。如果您正苦于以下问题:Python HTTPServer.stop方法的具体用法?Python HTTPServer.stop怎么用?Python HTTPServer.stop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tornado.httpserver.HTTPServer
的用法示例。
在下文中一共展示了HTTPServer.stop方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: WebsocketServer
# 需要导入模块: from tornado.httpserver import HTTPServer [as 别名]
# 或者: from tornado.httpserver.HTTPServer import stop [as 别名]
class WebsocketServer(tornado.web.Application):
def __init__(self, client_handler=ClientHandler, settings={}):
tornado.web.Application.__init__(
self,
[(WEBSOCKET_APPLICATION, client_handler, settings)],
debug=True)
self._loop = tornado.ioloop.IOLoop.instance()
self._listen(WEBSOCKET_PORT)
self.client_handlers = set()
def _listen(self, port, address="", **kwargs):
self._server = HTTPServer(self, **kwargs)
self._server.listen(port, address)
def start(self):
self._loop.start()
def stop(self):
self._loop.stop()
self._server.stop()
def add_periodic_callback(self, callback, callback_time):
periodic_callback = tornado.ioloop.PeriodicCallback(callback, callback_time, self._loop)
periodic_callback.start()
def client_subscribes_to(self, event_type):
for handler in self.client_handlers:
if event_type in handler.subscribed_events:
return True
示例2: SyncHTTPClientTest
# 需要导入模块: from tornado.httpserver import HTTPServer [as 别名]
# 或者: from tornado.httpserver.HTTPServer import stop [as 别名]
class SyncHTTPClientTest(unittest.TestCase):
def setUp(self):
self.server_ioloop = IOLoop()
event = threading.Event()
@gen.coroutine
def init_server():
sock, self.port = bind_unused_port()
app = Application([("/", HelloWorldHandler)])
self.server = HTTPServer(app)
self.server.add_socket(sock)
event.set()
def start():
self.server_ioloop.run_sync(init_server)
self.server_ioloop.start()
self.server_thread = threading.Thread(target=start)
self.server_thread.start()
event.wait()
self.http_client = HTTPClient()
def tearDown(self):
def stop_server():
self.server.stop()
# Delay the shutdown of the IOLoop by several iterations because
# the server may still have some cleanup work left when
# the client finishes with the response (this is noticeable
# with http/2, which leaves a Future with an unexamined
# StreamClosedError on the loop).
@gen.coroutine
def slow_stop():
# The number of iterations is difficult to predict. Typically,
# one is sufficient, although sometimes it needs more.
for i in range(5):
yield
self.server_ioloop.stop()
self.server_ioloop.add_callback(slow_stop)
self.server_ioloop.add_callback(stop_server)
self.server_thread.join()
self.http_client.close()
self.server_ioloop.close(all_fds=True)
def get_url(self, path):
return "http://127.0.0.1:%d%s" % (self.port, path)
def test_sync_client(self):
response = self.http_client.fetch(self.get_url("/"))
self.assertEqual(b"Hello world!", response.body)
def test_sync_client_error(self):
# Synchronous HTTPClient raises errors directly; no need for
# response.rethrow()
with self.assertRaises(HTTPError) as assertion:
self.http_client.fetch(self.get_url("/notfound"))
self.assertEqual(assertion.exception.code, 404)
示例3: _create_http_server
# 需要导入模块: from tornado.httpserver import HTTPServer [as 别名]
# 或者: from tornado.httpserver.HTTPServer import stop [as 别名]
def _create_http_server(self,port_start,port_end,ioloop):
import socket
server = HTTPServer(self.application, io_loop=ioloop)
for portnum in range(port_start, port_end):
try:
server.listen(portnum,
address=self._address_requested)
logger.info('Server listening on port {0}'.format(portnum))
self._port_used = portnum
self._address_used = self._address_requested
return server, portnum
except socket.error as e:
# try remaining ports if port used, raise otherwise
if e.errno != errno.EADDRINUSE or portnum == port_end-1:
logger.error(str(e)) # pragma: no cover
try:
server.stop()
except:
pass
raise
示例4: main
# 需要导入模块: from tornado.httpserver import HTTPServer [as 别名]
# 或者: from tornado.httpserver.HTTPServer import stop [as 别名]
def main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='config file')
args = parser.parse_args()
logger.warn('Reading config from {}'.format(args.config))
config = {}
with open(args.config, 'r') as infile:
config = json.load(infile)
if config == {}:
sys.exit()
serve_config = config.get('car_serve', {})
logger.warn(serve_config)
app = CarServer(config)
try:
logger.info('Opening HTTP server.')
http_server = HTTPServer(app)
http_server.listen(serve_config.get('port', 9001), address=serve_config.get('ip_address', '127.0.0.1'))
update_ms = serve_config.get('update_ms', 100)
logger.debug('Registering periodic callback. Every {} ms'.format(update_ms))
i = PeriodicCallback(app.car_state.update_physical_state, update_ms)
i.start()
IOLoop.current().start()
except (SystemExit, KeyboardInterrupt):
pass
logger.info('Stopping server.')
http_server.stop()
IOLoop.current().stop()
sys.exit(0)
示例5: FakeAnacondaServer
# 需要导入模块: from tornado.httpserver import HTTPServer [as 别名]
# 或者: from tornado.httpserver.HTTPServer import stop [as 别名]
class FakeAnacondaServer(object):
def __init__(self, io_loop, fail_these, expected_basename):
assert io_loop is not None
self.fail_these = fail_these
self.expected_basename = expected_basename
self._application = FakeAnacondaApplication(server=self, io_loop=io_loop)
self._http = HTTPServer(self._application, io_loop=io_loop)
# these would throw OSError on failure
sockets = bind_sockets(port=None, address='127.0.0.1')
self._port = None
for s in sockets:
# we have to find the ipv4 one
if s.family == socket.AF_INET:
self._port = s.getsockname()[1]
assert self._port is not None
self._http.add_sockets(sockets)
self._http.start(1)
@property
def port(self):
return self._port
@property
def url(self):
return "http://localhost:%d/" % self.port
def unlisten(self):
"""Permanently close down the HTTP server, no longer listen on any sockets."""
self._http.close_all_connections()
self._http.stop()
示例6: UIServer
# 需要导入模块: from tornado.httpserver import HTTPServer [as 别名]
# 或者: from tornado.httpserver.HTTPServer import stop [as 别名]
class UIServer(object):
def __init__(self, project, prepare_stage, event_handler, io_loop):
assert event_handler is not None
assert io_loop is not None
self._application = UIApplication(project, prepare_stage, event_handler, io_loop)
self._http = HTTPServer(self._application, io_loop=io_loop)
# these would throw OSError on failure
sockets = bind_sockets(port=None, address='127.0.0.1')
self._port = None
for s in sockets:
# we have to find the ipv4 one
if s.family == socket.AF_INET:
self._port = s.getsockname()[1]
assert self._port is not None
self._http.add_sockets(sockets)
self._http.start(1)
@property
def port(self):
return self._port
@property
def url(self):
return "http://localhost:%d/" % self.port
def unlisten(self):
"""Permanently close down the HTTP server, no longer listen on any sockets."""
self._http.close_all_connections()
self._http.stop()
示例7: __init__
# 需要导入模块: from tornado.httpserver import HTTPServer [as 别名]
# 或者: from tornado.httpserver.HTTPServer import stop [as 别名]
class Proxy:
def __init__(self, proxy_port, app_port):
self._proxy_port = proxy_port
self._app_port = app_port
def _create_app(self):
app = tornado.web.Application(
[
(r"/.*", MainHandler, dict(app_port=self._app_port))
],
xsrf_cookies=False,
debug=True)
return app
def serve_forever(self):
app = self._create_app()
self._server = HTTPServer(app)
self._server.listen(port=self._proxy_port, address='127.0.0.1')
self._ioloop = tornado.ioloop.IOLoop.instance()
self._ioloop.start() # this is a blocking call, server has stopped on next line
self._ioloop = None
def shutdown(self):
if self._ioloop:
self._server.stop()
self._ioloop.stop()
def run_on_a_thread(self):
process = multiprocessing.Process(target=self.serve_forever)
process.start()
time.sleep(1) # just let it start
return lambda: process.terminate()
示例8: HttpEndpoint
# 需要导入模块: from tornado.httpserver import HTTPServer [as 别名]
# 或者: from tornado.httpserver.HTTPServer import stop [as 别名]
class HttpEndpoint(object):
def __init__(self, uri='127.0.0.1:5000', backlog=128,
ssl_options=None):
# uri should be a list
if isinstance(uri, six.string_types):
self.uri = uri.split(",")
else:
self.uri = uri
self.backlog = backlog
self.ssl_options = ssl_options
self.server = None
self.loop = None
self.io_loop = None
def __str__(self):
return ",".join(self.uri)
def start(self, loop, app):
for uri in self.uri:
logger.info('Start new endpoint at http://%s', uri)
self.loop = loop
self.app = app
self.io_loop = IOLoop(_loop=loop)
self._start_server()
def _start_server(self):
self.server = HTTPServer(self.app, io_loop=self.io_loop,
ssl_options=self.ssl_options)
# bind the handler to needed interface
for uri in self.uri:
addr = parse_address(uri)
if isinstance(addr, six.string_types):
sock = netutil.bind_unix_socket(addr)
elif is_ipv6(addr[0]):
sock = netutil.bind_sockets(addr[1], address=addr[0],
family=socket.AF_INET6, backlog=self.backlog)
else:
sock = netutil.bind_sockets(addr[1], backlog=self.backlog)
if isinstance(sock, list):
for s in sock:
self.server.add_socket(s)
else:
self.server.add_socket(sock)
# start the server
self.server.start()
def stop(self):
self.server.stop()
self.io_loop.close()
def restart(self):
self.server.stop()
self._start_server()
示例9: run_server
# 需要导入模块: from tornado.httpserver import HTTPServer [as 别名]
# 或者: from tornado.httpserver.HTTPServer import stop [as 别名]
def run_server():
application = api.create_application()
http_server = HTTPServer(application)
http_server.listen(5000)
try:
SuperliminalCore.start_consumer()
IOLoop.current().start()
finally:
http_server.stop()
示例10: AsyncHTTPTestCase
# 需要导入模块: from tornado.httpserver import HTTPServer [as 别名]
# 或者: from tornado.httpserver.HTTPServer import stop [as 别名]
class AsyncHTTPTestCase(AsyncTestCase):
'''A test case that starts up an HTTP server.
Subclasses must override get_app(), which returns the
tornado.web.Application (or other HTTPServer callback) to be tested.
Tests will typically use the provided self.http_client to fetch
URLs from this server.
Example:
class MyHTTPTest(AsyncHTTPTestCase):
def get_app(self):
return Application([('/', MyHandler)...])
def test_homepage(self):
self.http_client.fetch(self.get_url('/'), self.stop)
response = self.wait()
# test contents of response
'''
def setUp(self):
super(AsyncHTTPTestCase, self).setUp()
self.__port = None
self.http_client = AsyncHTTPClient(io_loop=self.io_loop)
self._app = self.get_app()
self.http_server = HTTPServer(self._app, io_loop=self.io_loop,
**self.get_httpserver_options())
self.http_server.listen(self.get_http_port())
def get_app(self):
"""Should be overridden by subclasses to return a
tornado.web.Application or other HTTPServer callback.
"""
raise NotImplementedError()
def get_httpserver_options(self):
"""May be overridden by subclasses to return additional
keyword arguments for HTTPServer.
"""
return {}
def get_http_port(self):
"""Returns the port used by the HTTPServer.
A new port is chosen for each test.
"""
if self.__port is None:
self.__port = get_unused_port()
return self.__port
def get_url(self, path):
"""Returns an absolute url for the given path on the test server."""
return 'http://localhost:%s%s' % (self.get_http_port(), path)
def tearDown(self):
self.http_server.stop()
self.http_client.close()
super(AsyncHTTPTestCase, self).tearDown()
示例11: TestAgentSubscription
# 需要导入模块: from tornado.httpserver import HTTPServer [as 别名]
# 或者: from tornado.httpserver.HTTPServer import stop [as 别名]
class TestAgentSubscription(tornado.web.Application, Singleton):
pool_executor_cls = ThreadPoolExecutor
max_workers = 1
started = False
def __init__(self):
Singleton.__init__(self)
self.options = default_options
def configure(self, options, **kwargs):
Singleton.configure(self)
options = options if options else self.options
self.ssl = None
if options.subscription_server_cert and options.subscription_server_key:
self.ssl = dict(
certfile=abs_path(options.subscription_server_cert),
keyfile=abs_path(options.subscription_server_key)
)
if options.subscription_client_ca:
self.ssl["ca_certs"] = abs_path(options.subscription_client_ca)
self.ssl["cert_reqs"] = CERT_REQUIRED
tornado.web.Application.__init__(self, debug=options.debug, handlers=handlers, ssl_options=self.ssl)
self.started = False
self.options = options
atexit.register(self.stop)
self.http_server = HTTPServer(self, ssl_options=self.ssl)
@Singleton._if_configured(SubscriptionServiceException)
def start(self):
self.pool = self.pool_executor_cls(max_workers=self.max_workers)
self.listen(
self.options.subscription_port,
address=self.options.subscription_address,
ssl_options=self.ssl,
xheaders=True
)
logger.info("Subscription APIs available at http%s://%s:%s" % ('s' if self.ssl else '', self.options.subscription_address, self.options.subscription_port))
self.started = True
@Singleton._if_configured(SubscriptionServiceException)
def listen(self, port, address="", **kwargs):
self.http_server.listen(port, address)
@Singleton._if_configured(SubscriptionServiceException)
def stop(self):
if self.started:
self.http_server.close_all_connections()
self.http_server.stop()
self.pool.shutdown(wait=False)
self.started = False
@Singleton._if_configured(SubscriptionServiceException)
def delay(self, method, *args, **kwargs):
return self.pool.submit(partial(method, *args, **kwargs))
示例12: SyncHTTPClientTest
# 需要导入模块: from tornado.httpserver import HTTPServer [as 别名]
# 或者: from tornado.httpserver.HTTPServer import stop [as 别名]
class SyncHTTPClientTest(unittest.TestCase):
def setUp(self):
if IOLoop.configured_class().__name__ in ('TwistedIOLoop',
'AsyncIOMainLoop'):
# TwistedIOLoop only supports the global reactor, so we can't have
# separate IOLoops for client and server threads.
# AsyncIOMainLoop doesn't work with the default policy
# (although it could with some tweaks to this test and a
# policy that created loops for non-main threads).
raise unittest.SkipTest(
'Sync HTTPClient not compatible with TwistedIOLoop or '
'AsyncIOMainLoop')
self.server_ioloop = IOLoop()
sock, self.port = bind_unused_port()
app = Application([('/', HelloWorldHandler)])
self.server = HTTPServer(app, io_loop=self.server_ioloop)
self.server.add_socket(sock)
self.server_thread = threading.Thread(target=self.server_ioloop.start)
self.server_thread.start()
self.http_client = HTTPClient()
def tearDown(self):
def stop_server():
self.server.stop()
# Delay the shutdown of the IOLoop by one iteration because
# the server may still have some cleanup work left when
# the client finishes with the response (this is noticable
# with http/2, which leaves a Future with an unexamined
# StreamClosedError on the loop).
self.server_ioloop.add_callback(self.server_ioloop.stop)
self.server_ioloop.add_callback(stop_server)
self.server_thread.join()
self.http_client.close()
self.server_ioloop.close(all_fds=True)
def get_url(self, path):
return 'http://127.0.0.1:%d%s' % (self.port, path)
def test_sync_client(self):
response = self.http_client.fetch(self.get_url('/'))
self.assertEqual(b'Hello world!', response.body)
def test_sync_client_error(self):
# Synchronous HTTPClient raises errors directly; no need for
# response.rethrow()
with self.assertRaises(HTTPError) as assertion:
self.http_client.fetch(self.get_url('/notfound'))
self.assertEqual(assertion.exception.code, 404)
示例13: main
# 需要导入模块: from tornado.httpserver import HTTPServer [as 别名]
# 或者: from tornado.httpserver.HTTPServer import stop [as 别名]
def main():
"""
This program will run the GPUVerify Rise4Fun web service
as a production server which uses Tornado as the HTTP
server.
"""
import argparse
parser = argparse.ArgumentParser(description=main.__doc__)
parser.add_argument('-p', '--port', type=int, default=5000, help='Port to use. Default %(default)s')
parser.add_argument('-f', '--forks', type=int, default=0, help='Number of processes to use. A value of zero will use the number of available cores on the machine. Default %(default)s')
parser.add_argument("-l","--log-level",type=str, default="INFO",choices=['debug','info','warning','error'])
parser.add_argument("-o","--log-output",type=str, default='-', help='Write logging information to file. "-" means standard output. Default "%(default)s"')
args = parser.parse_args()
# Setup loging file
logStream=None
try:
if args.log_output == '-':
logStream=sys.stdout
else:
logStream = open(args.log_output,mode='a') # Append
# Setup the root logger before importing app so that the loggers used in app
# and its dependencies have a handler set
logging.basicConfig(level=getattr(logging,args.log_level.upper(),None),
stream=logStream,
format='%(asctime)s:%(name)s:%(levelname)s:%(module)s.%(funcName)s() : (PID %(process)d) %(message)s')
logging.info("Starting GPUVerifyRise4Fun")
from webservice import app
# Add signal handler for SIGTERM that will trigger the same exception that SIGINT does
def terminate(signum,frame):
logging.info("PID " + str(os.getpid()) + "Received signal " + str(signum))
raise KeyboardInterrupt()
signal.signal(signal.SIGTERM,terminate)
try:
logging.info("Starting server on port " + str(args.port))
http_server = HTTPServer(WSGIContainer(app))
http_server.bind(args.port)
http_server.start(args.forks) # Fork multiple sub-processes
IOLoop.instance().start()
except KeyboardInterrupt:
http_server.stop()
logging.info("Exiting process:" + str(os.getpid()) )
finally:
logStream.close()
示例14: __init__
# 需要导入模块: from tornado.httpserver import HTTPServer [as 别名]
# 或者: from tornado.httpserver.HTTPServer import stop [as 别名]
class server:
def __init__(self, cfg):
self.cfg = cfg
handler_args = {'cfg':self.cfg}
self.application = tornado.web.Application([
(r"/jsonrpc", JSONRPCHandler, handler_args),
(r"/.*", DefaultHandler, handler_args),
])
def start(self):
self.http_server = HTTPServer(self.application, xheaders=True)
self.http_server.listen(self.cfg["options"].port)
IOLoop.instance().start()
def stop(self):
self.http_server.stop()
IOLoop.instance().stop()
示例15: UnixSocketTest
# 需要导入模块: from tornado.httpserver import HTTPServer [as 别名]
# 或者: from tornado.httpserver.HTTPServer import stop [as 别名]
class UnixSocketTest(AsyncTestCase):
"""HTTPServers can listen on Unix sockets too.
Why would you want to do this? Nginx can proxy to backends listening
on unix sockets, for one thing (and managing a namespace for unix
sockets can be easier than managing a bunch of TCP port numbers).
Unfortunately, there's no way to specify a unix socket in a url for
an HTTP client, so we have to test this by hand.
"""
def setUp(self):
super(UnixSocketTest, self).setUp()
self.tmpdir = tempfile.mkdtemp()
self.sockfile = os.path.join(self.tmpdir, "test.sock")
sock = netutil.bind_unix_socket(self.sockfile)
app = Application([("/hello", HelloWorldRequestHandler)])
self.server = HTTPServer(app)
self.server.add_socket(sock)
self.stream = IOStream(socket.socket(socket.AF_UNIX))
self.stream.connect(self.sockfile, self.stop)
self.wait()
def tearDown(self):
self.stream.close()
self.io_loop.run_sync(self.server.close_all_connections)
self.server.stop()
shutil.rmtree(self.tmpdir)
super(UnixSocketTest, self).tearDown()
def test_unix_socket(self):
self.stream.write(b"GET /hello HTTP/1.0\r\n\r\n")
self.stream.read_until(b"\r\n", self.stop)
response = self.wait()
self.assertEqual(response, b"HTTP/1.1 200 OK\r\n")
self.stream.read_until(b"\r\n\r\n", self.stop)
headers = HTTPHeaders.parse(self.wait().decode('latin1'))
self.stream.read_bytes(int(headers["Content-Length"]), self.stop)
body = self.wait()
self.assertEqual(body, b"Hello world")
def test_unix_socket_bad_request(self):
# Unix sockets don't have remote addresses so they just return an
# empty string.
with ExpectLog(gen_log, "Malformed HTTP message from"):
self.stream.write(b"garbage\r\n\r\n")
self.stream.read_until_close(self.stop)
response = self.wait()
self.assertEqual(response, b"HTTP/1.1 400 Bad Request\r\n\r\n")