python类httpserver()的实例源码

md_editor.py 文件源码 项目:md_editor 作者: kghch 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def main():
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(9876)
    tornado.ioloop.IOLoop.current().start()
demo.py 文件源码 项目:tensorflow-pspnet 作者: pudae 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
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()
tornado.py 文件源码 项目:SuperOcto 作者: mcecchi 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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)
tornado.py 文件源码 项目:SuperOcto 作者: mcecchi 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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


问题


面经


文章

微信
公众号

扫码关注公众号