我们从Python开源项目中,提取了以下34个代码示例,用于说明如何使用tornado.httpserver()。
def listen(self, port, address="", **kwargs): """Starts an HTTP server for this application on the given port. This is a convenience alias for creating an `.HTTPServer` object and calling its listen method. Keyword arguments not supported by `HTTPServer.listen <.TCPServer.listen>` are passed to the `.HTTPServer` constructor. For advanced uses (e.g. multi-process mode), do not use this method; create an `.HTTPServer` and call its `.TCPServer.bind`/`.TCPServer.start` methods directly. Note that after calling this method you still need to call ``IOLoop.current().start()`` to start the server. Returns the `.HTTPServer` object. .. versionchanged:: 4.3 Now returns the `.HTTPServer` object. """ # import is here rather than top level because HTTPServer # is not importable on appengine from tornado.httpserver import HTTPServer server = HTTPServer(self, **kwargs) server.listen(port, address) return server
def shutdown(ioloop, server): ''' ??server :param server: tornado.httpserver.HTTPServer ''' logging.info( "HTTP interpreter service will shutdown in %ss...", 1) server.stop() deadline = time.time() + 1 def stop_loop(): ''' ????loop ''' now = time.time() if now < deadline and (ioloop._callbacks or ioloop._timeouts): ioloop.add_timeout(now + 1, stop_loop) else: # ?????? callback ? timeout ? ioloop.stop() logging.info('Shutdown!') stop_loop()
def main(): ''' main ?? ''' # ?? search_engin_server ioloop = tornado.ioloop.IOLoop.instance() server = tornado.httpserver.HTTPServer(Application(), xheaders=True) server.listen(options.port) def sig_handler(sig, _): ''' ?????? ''' logging.warn("Caught signal: %s", sig) shutdown(ioloop, server) signal.signal(signal.SIGTERM, sig_handler) signal.signal(signal.SIGINT, sig_handler) ioloop.start()
def listen(self, port, address="", **kwargs): """Starts an HTTP server for this application on the given port. This is a convenience alias for creating an HTTPServer object and calling its listen method. Keyword arguments not supported by HTTPServer.listen are passed to the HTTPServer constructor. For advanced uses (e.g. preforking), do not use this method; create an HTTPServer and call its bind/start methods directly. Note that after calling this method you still need to call IOLoop.instance().start() to start the server. """ # import is here rather than top level because HTTPServer # is not importable on appengine from tornado.httpserver import HTTPServer server = HTTPServer(self, **kwargs) server.listen(port, address)
def listen(self, port, address="", **kwargs): """Starts an HTTP server for this application on the given port. This is a convenience alias for creating an `.HTTPServer` object and calling its listen method. Keyword arguments not supported by `HTTPServer.listen <.TCPServer.listen>` are passed to the `.HTTPServer` constructor. For advanced uses (e.g. multi-process mode), do not use this method; create an `.HTTPServer` and call its `.TCPServer.bind`/`.TCPServer.start` methods directly. Note that after calling this method you still need to call ``IOLoop.instance().start()`` to start the server. """ # import is here rather than top level because HTTPServer # is not importable on appengine from tornado.httpserver import HTTPServer server = HTTPServer(self, **kwargs) server.listen(port, address)
def listen(self, port, address="", **kwargs): """Starts an HTTP server for this application on the given port. This is a convenience alias for creating an `.HTTPServer` object and calling its listen method. Keyword arguments not supported by `HTTPServer.listen <.TCPServer.listen>` are passed to the `.HTTPServer` constructor. For advanced uses (e.g. multi-process mode), do not use this method; create an `.HTTPServer` and call its `.TCPServer.bind`/`.TCPServer.start` methods directly. Note that after calling this method you still need to call ``IOLoop.current().start()`` to start the server. """ # import is here rather than top level because HTTPServer # is not importable on appengine from tornado.httpserver import HTTPServer server = HTTPServer(self, **kwargs) server.listen(port, address)
def listen(cls, tornado_port): """ Start the Tornado HTTP server on given port. :param tornado_port: Port to listen :type tornado_port: int :return: None .. todo:: Add support for HTTPS server. """ if not cls.app: raise TypeError('Tornado application was not instantiated, call TornadoWrapper.start_app method.') cls.server = tornado.httpserver.HTTPServer(cls.app) cls.server.listen(tornado_port)
def main(): define(name='port', default=8000, type=int, help='run on the given port') tornado.options.parse_command_line() logger.info('================ spider web server has started ================ ') logger.info(' server start at port -> {}, debug mode = {}'.format(options.port, constants.DEBUG)) app = make_web_app() http_server = tornado.httpserver.HTTPServer(app) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start()
def main(port): #train() load_grocery() tornado.options.parse_command_line() print "start on port %s..." % port http_server = tornado.httpserver.HTTPServer(Application(), xheaders=True) http_server.listen(port) #tornado.autoreload.start() tornado.ioloop.IOLoop.instance().start()
def cookies(self): """An alias for `self.request.cookies <.httpserver.HTTPRequest.cookies>`.""" return self.request.cookies
def run_wsgi(wsgi_app, port): """Runs wsgi (Flask) app using tornado web server.""" container = tornado.wsgi.WSGIContainer(wsgi_app) app = tornado.web.Application([ (r".*", tornado.web.FallbackHandler, dict(fallback=container)), ]) http_server = tornado.httpserver.HTTPServer(app) http_server.listen(port) tornado.ioloop.IOLoop.instance().start()
def run_wsgi_unix(wsgi_app, socket): """Runs wsgi (Flask) app using tornado unixsocket web server.""" container = tornado.wsgi.WSGIContainer(wsgi_app) app = tornado.web.Application([ (r".*", tornado.web.FallbackHandler, dict(fallback=container)), ]) http_server = tornado.httpserver.HTTPServer(app) unix_socket = tornado.netutil.bind_unix_socket(socket) http_server.add_socket(unix_socket) tornado.ioloop.IOLoop.instance().start()
def handle_stream(self, stream, address): context = tornado.httpserver._HTTPRequestContext(stream, address, self.protocol) conn = CustomHTTP1ServerConnection( stream, self.conn_params, context) self._connections.add(conn) conn.start_serving(self)
def test_listen_with_app_instance(self, stub): self.assertIsNone(TornadoWrapper.app) self.assertIsNone(TornadoWrapper.server) TornadoWrapper.start_app() TornadoWrapper.listen(12345) self.assertIsInstance(TornadoWrapper.app, tornado.web.Application) self.assertIs(stub, tornado.httpserver.HTTPServer) stub.assert_called_with(TornadoWrapper.app)
def main(): http_server = tornado.httpserver.HTTPServer(Application()) http_server.listen(9876) tornado.ioloop.IOLoop.current().start()
def main(): """main""" parser = configargparse.ArgParser( default_config_files=[ os.path.join(CURRENT_DIR, "server.conf"), "server.conf", "/etc/skynet/server.conf"]) parser.add("--debug", dest="debug", default=False, action="store_true") parser.add("--no-debug", dest="debug", action="store_false") parser.add("--log", dest="log", default="") parser.add("--host", dest="host", default=os.environ.get("BIND", "127.0.0.1")) parser.add("--port", dest="port", type=int, default=int(os.environ.get("PORT", 80))) parser.add("--model", dest="model", required=True) parser.add("--gpu", dest="gpu", default=True, action="store_true") parser.add("--no-gpu", dest="gpu", action="store_false") parser.add("--gpu-memory-fraction", type=float, default=0.40, dest="gpu_memory_fraction") config = vars(parser.parse_args()) setup_log(config["log"]) logging.info("config: %s", config) app = App(config) server = httpserver.HTTPServer(app.http_app()) server.bind(config["port"], address=config["host"]) server.start() logging.info("Server Start! Listen: %s", [x.getsockname() for x in server._sockets.values()]) # pylint: disable=protected-access tornado.ioloop.IOLoop.current().start()
def __call__(self, request, body=None): """ Wraps the call against the WSGI app, deriving the WSGI environment from the supplied Tornado ``HTTPServerRequest``. :param request: the ``tornado.httpserver.HTTPServerRequest`` to derive the WSGI environment from :param body: an optional body to use as ``wsgi.input`` instead of ``request.body``, can be a string or a stream """ data = {} response = [] def start_response(status, response_headers, exc_info=None): data["status"] = status data["headers"] = response_headers return response.append app_response = self.wsgi_application( WsgiInputContainer.environ(request, body), start_response) try: response.extend(app_response) body = b"".join(response) finally: if hasattr(app_response, "close"): app_response.close() if not data: raise Exception("WSGI app did not call start_response") status_code = int(data["status"].split()[0]) headers = data["headers"] header_set = set(k.lower() for (k, v) in headers) body = tornado.escape.utf8(body) if status_code != 304: if "content-length" not in header_set: headers.append(("Content-Length", str(len(body)))) if "content-type" not in header_set: headers.append(("Content-Type", "text/html; charset=UTF-8")) if "server" not in header_set: headers.append(("Server", "TornadoServer/%s" % tornado.version)) parts = [tornado.escape.utf8("HTTP/1.1 " + data["status"] + "\r\n")] for key, value in headers: parts.append(tornado.escape.utf8(key) + b": " + tornado.escape.utf8(value) + b"\r\n") parts.append(b"\r\n") parts.append(body) request.write(b"".join(parts)) request.finish() self._log(status_code, request)
def environ(request, body=None): """ Converts a ``tornado.httputil.HTTPServerRequest`` to a WSGI environment. An optional ``body`` to be used for populating ``wsgi.input`` can be supplied (either a string or a stream). If not supplied, ``request.body`` will be wrapped into a ``io.BytesIO`` stream and used instead. :param request: the ``tornado.httpserver.HTTPServerRequest`` to derive the WSGI environment from :param body: an optional body to use as ``wsgi.input`` instead of ``request.body``, can be a string or a stream """ from tornado.wsgi import to_wsgi_str import sys import io # determine the request_body to supply as wsgi.input if body is not None: if isinstance(body, (bytes, str, unicode)): request_body = io.BytesIO(tornado.escape.utf8(body)) else: request_body = body else: request_body = io.BytesIO(tornado.escape.utf8(request.body)) hostport = request.host.split(":") if len(hostport) == 2: host = hostport[0] port = int(hostport[1]) else: host = request.host port = 443 if request.protocol == "https" else 80 environ = { "REQUEST_METHOD": request.method, "SCRIPT_NAME": "", "PATH_INFO": to_wsgi_str(tornado.escape.url_unescape( request.path, encoding=None, plus=False)), "QUERY_STRING": request.query, "REMOTE_ADDR": request.remote_ip, "SERVER_NAME": host, "SERVER_PORT": str(port), "SERVER_PROTOCOL": request.version, "wsgi.version": (1, 0), "wsgi.url_scheme": request.protocol, "wsgi.input": request_body, "wsgi.errors": sys.stderr, "wsgi.multithread": False, "wsgi.multiprocess": True, "wsgi.run_once": False, } if "Content-Type" in request.headers: environ["CONTENT_TYPE"] = request.headers.pop("Content-Type") if "Content-Length" in request.headers: environ["CONTENT_LENGTH"] = request.headers.pop("Content-Length") for key, value in request.headers.items(): environ["HTTP_" + key.replace("-", "_").upper()] = value return environ