• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python httpserver.HTTPServer类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中tornado.httpserver.HTTPServer的典型用法代码示例。如果您正苦于以下问题:Python HTTPServer类的具体用法?Python HTTPServer怎么用?Python HTTPServer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了HTTPServer类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: http_server

def http_server(io_loop, listener, ssl_options=None, registration_db=None):

    # initialize the registry
    registration_db = registration_db or Registry(loop=io_loop._loop)

    # lookup routes
    user_settings = { "registration_db": registration_db }
    lookup_router = sockjs.SockJSRouter(LookupConnection, "/lookup",
            io_loop=io_loop, user_settings=user_settings)

    # initialize handlers
    handlers = [
            (r'/', WelcomeHandler),
            (r'/ping', PingHandler),
            (r'/version', VersionHandler),
            (r'/nodes', NodesHandler),
            (r'/sessions', SessionsHandler),
            (r'/sessions/([^/]+)', SessionsHandler),
            (r'/jobs', JobsHandler),
            (r'/findJob', FindJobHandler),
            (r'/findSession', FindSessionHandler),
            (r'/ws', LookupWebSocket)] + lookup_router.urls

    # initialize the server
    app = Application(handlers, registration_db=registration_db)
    server = HTTPServer(app, io_loop=io_loop, ssl_options=ssl_options)
    server.add_sockets(listener)
    return server
开发者ID:adamchainz,项目名称:gaffer,代码行数:28,代码来源:http.py


示例2: __init__

    def __init__(self, listener, application=None, backlog=2048,
                 socket_type=socket.SOCK_STREAM,
                 address_family=socket.AF_INET):
        self.address_family = address_family
        self.socket_type = socket_type
        host, port = listener

        if isinstance(application, Application):
            self._server = HTTPServer(application)
        elif isinstance(application, TCPServer):
            self._server = application
        elif callable(application):
            tapp = tornado.wsgi.WSGIContainer(application)
            self._server = HTTPServer(tapp)
        else:
            raise TypeError(
                "Unsupported application type: %r" % (application,))

        if host.startswith('fd://'):
            fd = int(host.split('://')[1])
            set_close_exec(fd)
            sock = socket.fromfd(fd, address_family, socket_type)
            sock.setblocking(0)
            socks = [sock]
        elif self.address_family == socket.AF_UNIX:
            filename = host[len('unix:'):]
            sock = tornado.netutil.bind_unix_socket(filename, backlog=backlog)
            socks = [sock]
        else:
            socks = tornado.netutil.bind_sockets(
                port, host, address_family, backlog)
        self._server.add_sockets(socks)
        self.application = application
开发者ID:atomd,项目名称:chaussette,代码行数:33,代码来源:_tornado.py


示例3: _go

def _go(args):
    app = create_app(args)
    port = app.app.config['PORT']
    app.setup()

    mode = app.app.config['SERVER']
    if args.mode == 'dev':
        mode = 'development'
        app.app.config['DEBUG'] = True
    elif args.mode == 'prd':
        mode = 'production'

    if mode == 'development':
        print("Starting development server on port %d..." % port)
        app.app.run(port=port)
    elif mode == 'production':
        appl = WSGIContainer(app.app)
        if 'SSL_KEY' in app.app.config:
            http_server = HTTPServer(appl, ssl_options={
                "certfile": app.app.config['SSL_CRT'],
                "keyfile": app.app.config['SSL_KEY'],
            })
        else:
            http_server = HTTPServer(appl)
        http_server.listen(port)
        print("Starting production server on port %d..." % port)
        IOLoop.instance().start()
    else:
        sys.stderr.write("Invalid SERVER setting '%s', aborting.\n" % args.mode)
        sys.exit(1)
开发者ID:edbutler,项目名称:papika-telemetry,代码行数:30,代码来源:main.py


示例4: startTornado

def startTornado():
    global http_server
    http_server = HTTPServer(WSGIContainer(create_app("settings.DevelopmentConfig")))
    http_server.listen(80)
    ioloop = IOLoop.instance()
    autoreload.start(ioloop)
    ioloop.start()
开发者ID:emmdim,项目名称:wibed-controller,代码行数:7,代码来源:tornadoserver.py


示例5: runserver

def runserver():
    http_server = HTTPServer(Application(), xheaders=True)
    http_server.listen(options.port)
    
    loop = tornado.ioloop.IOLoop.instance()
    
    def shutdown():
        logging.info('Server stopping ...')
        http_server.stop()
        
        logging.info('IOLoop wil  be terminate in 1 seconds')   
        deadline = time.time() + 1
        
        def terminate():
            now = time.time()
            
            if now < deadline and (loop._callbacks or loop._timeouts):
                loop.add_timeout(now + 1, terminate)
            else:
                loop.stop()
                logging.info('Server shutdown')
        
        terminate()
    
    def sig_handler(sig, frame):
        logging.warn('Caught signal:%s', sig)
        loop.add_callback(shutdown)
    
    signal.signal(signal.SIGINT, sig_handler)
    signal.signal(signal.SIGTERM, sig_handler)
    
    logging.info('Server running on http://0.0.0.0:%d'%(options.port))
    loop.start()
开发者ID:UniqueLJH,项目名称:yinongShop,代码行数:33,代码来源:manager.py


示例6: main

def main():
    '''Create server, begin IOLoop 
    '''
    tornado.options.parse_command_line()
    http_server = HTTPServer(Application(), xheaders=True)
    http_server.listen(options.port)
    IOLoop.instance().start()
开发者ID:nsliwa,项目名称:Explore-SMU,代码行数:7,代码来源:tornado_LearnServer.py


示例7: zoe_web_main

def zoe_web_main() -> int:
    """
    This is the entry point for the Zoe Web script.
    :return: int
    """
    load_configuration()
    args = get_conf()
    if args.debug:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.INFO)
    logging.getLogger("requests").setLevel(logging.WARNING)
    logging.getLogger("tornado").setLevel(logging.DEBUG)

    log.info("Starting HTTP server...")
    app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
    app.secret_key = args.cookie_secret

    http_server = HTTPServer(WSGIContainer(app))
    http_server.listen(args.listen_port, args.listen_address)
    ioloop = IOLoop.instance()
    try:
        ioloop.start()
    except KeyboardInterrupt:
        print("CTRL-C detected, terminating")
开发者ID:ddcy,项目名称:zoe,代码行数:25,代码来源:entrypoint.py


示例8: main

def main(arguments=None):
    """Runs thumbor server with the specified arguments."""

    server_parameters = get_server_parameters(arguments)
    logging.basicConfig(level=getattr(logging, server_parameters.log_level.upper()))

    lookup_paths = [os.curdir, expanduser("~"), "/etc/", dirname(__file__)]

    config = Config.load(server_parameters.config_path, conf_name="thumbor.conf", lookup_paths=lookup_paths)
    importer = Importer(config)
    importer.import_modules()

    if server_parameters.security_key is None:
        server_parameters.security_key = config.SECURITY_KEY

    if not isinstance(server_parameters.security_key, basestring):
        raise RuntimeError(
            "No security key was found for this instance of thumbor. Please provide one using the conf file or a security key file."
        )

    context = Context(server=server_parameters, config=config, importer=importer)
    application = ThumborServiceApp(context)

    server = HTTPServer(application)
    server.bind(context.server.port, context.server.ip)
    server.start(1)

    try:
        logging.debug("thumbor running at %s:%d" % (context.server.ip, context.server.port))
        tornado.ioloop.IOLoop.instance().start()
    except KeyboardInterrupt:
        print
        print "-- thumbor closed by user interruption --"
开发者ID:brunomvsouza,项目名称:thumbor,代码行数:33,代码来源:server.py


示例9: __init__

class ServerManager:
    """
    The server manager is responsible for bootstraping the tornado webserver
    with a wsgi container on the given port. Currently the server manager is
    only able to instanciate one instance on one port. Multiple instances
    are not supported.
    """

    def __init__(self):
        self._http_server = HTTPServer(WSGIContainer(app))

    def start_server(self, portapi=5000, mode="development"):
        """
        starts the tornado webserver with wsgi container on the specified mode.
        The mode determines which configuration should be used by the api. Possible values are
        - development
        - staging
        - production
        :param portapi: port where the server should listen on. Default is 5000
        :param mode: defines the mode on which the server should run on
        :return: Nothing
        """
        set_app_mode(mode)

        self._http_server.listen(portapi)
        IOLoop.instance().start()
开发者ID:JungesAngebot,项目名称:lwjgl-REST,代码行数:26,代码来源:views.py


示例10: start_server

def start_server():
    ''' Main entry point for the application '''
    sockets = netutil.bind_sockets(config.listen_port)
    server = HTTPServer(app)
    server.add_sockets(sockets)
    io_loop = IOLoop.instance()
    scoring = PeriodicCallback(
        scoring_round, int(5 * 60 * 1000), io_loop=io_loop
    )
    scoring.start()
    try:
        sys.stdout.write("\r" + INFO + "The game has begun, good hunting!\n")
        if config.debug:
            sys.stdout.write(WARN + "WARNING: Debug mode is enabled.\n")
        sys.stdout.flush()
        game_history = GameHistory.Instance()
        history_callback = PeriodicCallback(
            game_history.take_snapshot, int(60 * 1000), io_loop=io_loop
        )
        history_callback.start()
        io_loop.start()
    except KeyboardInterrupt:
        print('\r' + WARN + 'Shutdown Everything!')
    except:
      logging.exception("Main i/o loop threw exception")
    finally:
        io_loop.stop()
        if config.debug and \
                raw_input(PROMPT + "Flush Memcache? [Y/n]: ").lower() == 'y':
            print(INFO + 'Flushing cache ...'),
            FileCache.flush()
            print('OK')
        _exit(0)
开发者ID:mach327,项目名称:RootTheBox,代码行数:33,代码来源:__init__.py


示例11: run_tornado

def run_tornado(addr, port, *args, **kwargs):
    """
    Starts the tornado webserver as wsgi server for OpenSlides.

    It runs in one thread.
    """
    # Save the port and the addr in a global var
    global RUNNING_HOST, RUNNING_PORT
    RUNNING_HOST = addr
    RUNNING_PORT = port

    # Don't try to read the command line args from openslides
    parse_command_line(args=[])

    # Setup WSGIContainer
    app = WSGIContainer(get_wsgi_application())

    # Collect urls
    sock_js_router = SockJSRouter(OpenSlidesSockJSConnection, '/sockjs')
    other_urls = [
        (r'%s(.*)' % settings.STATIC_URL, DjangoStaticFileHandler),
        (r'%s(.*)' % settings.MEDIA_URL, StaticFileHandler, {'path': settings.MEDIA_ROOT}),
        ('.*', FallbackHandler, dict(fallback=app))]

    # Start the application
    debug = settings.DEBUG
    tornado_app = Application(sock_js_router.urls + other_urls, autoreload=debug, debug=debug)
    server = HTTPServer(tornado_app)
    server.listen(port=port, address=addr)
    IOLoop.instance().start()

    # Reset the global vars
    RUNNING_HOST = None
    RUNNING_PORT = None
开发者ID:chyka-dev,项目名称:OpenSlides,代码行数:34,代码来源:autoupdate.py


示例12: Server

class Server():
    def __init__(self, configfile=None, basedir=None, host="0.0.0.0", port=5000, debug=False, allowRoot=False):
        self._app = app
        self._configfile = configfile
        self._basedir = basedir 
        self._host = host
        self._port = port
        self._debug = debug
        self._allowRoot = allowRoot
    
    def run(self):

        from tornado.wsgi import WSGIContainer
        from tornado.httpserver import HTTPServer
        from tornado.ioloop import IOLoop
        from tornado.web import Application, FallbackHandler
        app.debug=self._debug

        self._router = SockJSRouter(self._createSocketConnection, "/sockjs")
        # app.run(host=self._host, port=self._port, server="tornado",reloader=self._debug)
        self._tornado_app = Application(self._router.urls + [
            (r".*", FallbackHandler, {"fallback": WSGIContainer(app)})
            ])
        self._server = HTTPServer(self._tornado_app)
        self._server.listen(self._port, address=self._host)
        IOLoop.instance().start() 

    def _createSocketConnection(self, session):
        return PiMillSocket(session)
开发者ID:fibasile,项目名称:pi.mill,代码行数:29,代码来源:server.py


示例13: create_async_client

def create_async_client(path, station_coordinates_callback=None,
                        event_info_callback=None,
                        travel_time_callback=None):
    application = get_application()
    application.db = InstaseisDB(path)
    application.station_coordinates_callback = station_coordinates_callback
    application.event_info_callback = event_info_callback
    application.travel_time_callback = travel_time_callback
    application.max_size_of_finite_sources = 1000
    # Build server as in testing:311
    sock, port = bind_unused_port()
    server = HTTPServer(application, io_loop=IOLoop.instance())
    server.add_sockets([sock])
    client = AsyncClient(server, AsyncHTTPClient())
    client.application = application
    client.filepath = path
    client.port = port
    # Flag to help deal with forward/backwards databases.
    if "bwd" in os.path.basename(path):
        client.is_reciprocal = True
        client.source_depth = 0.0
    else:
        client.is_reciprocal = False
        client.source_depth = application.db.info.source_depth * 1000
    client.info = application.db.info
    return client
开发者ID:MMesch,项目名称:instaseis,代码行数:26,代码来源:tornado_testing_fixtures.py


示例14: main

def main(arguments=None):
    '''Runs r³ server with the specified arguments.'''

    parser = argparse.ArgumentParser(description='runs the application that processes stream requests for r³')
    parser.add_argument('-b', '--bind', type=str, default='0.0.0.0', help='the ip that r³ will bind to')
    parser.add_argument('-p', '--port', type=int, default=9999, help='the port that r³ will bind to')
    parser.add_argument('-l', '--loglevel', type=str, default='warning', help='the log level that r³ will run under')
    parser.add_argument('-i', '--hide-index-page', action='store_true', default=False, help='indicates whether r³ app should show the help page')
    parser.add_argument('-d', '--debug', action='store_true', default=False, help='indicates whether r³ app should run in debug mode')
    parser.add_argument('--redis-host', type=str, default='0.0.0.0', help='the ip that r³ will use to connect to redis')
    parser.add_argument('--redis-port', type=int, default=6379, help='the port that r³ will use to connect to redis')
    parser.add_argument('--redis-db', type=int, default=0, help='the database that r³ will use to connect to redis')
    parser.add_argument('--redis-pass', type=str, default='', help='the password that r³ will use to connect to redis')
    parser.add_argument('-c', '--config-file', type=str, help='the config file that r³ will use to load input stream classes and reducers', required=True)

    args = parser.parse_args(arguments)

    cfg = Config(args.config_file)

    c = redis.StrictRedis(host=args.redis_host, port=args.redis_port, db=args.redis_db, password=args.redis_pass)

    logging.basicConfig(level=getattr(logging, args.loglevel.upper()))

    application = R3ServiceApp(redis=c, config=cfg, log_level=args.loglevel.upper(), debug=args.debug, show_index_page=not args.hide_index_page)

    server = HTTPServer(application)
    server.bind(args.port, args.bind)
    server.start(1)

    try:
        logging.debug('r³ service app running at %s:%d' % (args.bind, args.port))
        tornado.ioloop.IOLoop.instance().start()
    except KeyboardInterrupt:
        print
        print "-- r³ service app closed by user interruption --"
开发者ID:Fangang,项目名称:r3,代码行数:35,代码来源:server.py


示例15: _create_http_server

    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
开发者ID:karelin,项目名称:Exhibitionist,代码行数:25,代码来源:server.py


示例16: runserver

def runserver():
    tornado.options.parse_command_line()
    http_server = HTTPServer(Application(), xheaders=True)
    http_server.listen(options.port)
    loop = tornado.ioloop.IOLoop.instance()
    print 'Server running on http://localhost:%d' % (options.port)
    loop.start()
开发者ID:onary,项目名称:boilerplate,代码行数:7,代码来源:manage.py


示例17: main

def main():
    global http_server

    try:
        signal(SIGTERM, on_signal)

        parse_command_line()
        if options.config != None:
            parse_config_file(options.config)

        path = join(dirname(__file__), "templates")

        application = Application(
            [(r"/", IndexHandler), (r"/stock", StockHandler)],
            template_path=path,
            static_path=join(dirname(__file__), "static"),
        )

        application.db = motor.MotorClient(options.db_host, options.db_port).open_sync()[options.db_name]

        http_server = HTTPServer(application)
        http_server.listen(options.port, options.address)
        log().info("server listening on port %s:%d" % (options.address, options.port))
        if log().isEnabledFor(DEBUG):
            log().debug("autoreload enabled")
            tornado.autoreload.start()
        IOLoop.instance().start()

    except KeyboardInterrupt:
        log().info("exiting...")

    except BaseException as ex:
        log().error("exiting due: [%s][%s]" % (str(ex), str(format_exc().splitlines())))
        exit(1)
开发者ID:irr,项目名称:stock-labs,代码行数:34,代码来源:Server.py


示例18: setup_server

def setup_server():
    # Config tornado.curl_httpclient to use NullHandler
    tornado_logger = logging.getLogger('tornado.curl_httpclient')
    tornado_logger.addHandler(logging.NullHandler())
    tornado_logger.propagate = False

    settings = dict(
        autoreload=True,
        secret="ElasticKube",
    )

    configure(settings)

    handlers = [
        (r"/api/v1/auth/providers", AuthProvidersHandler),
        (r"/api/v1/auth/signup", SignupHandler),
        (r"/api/v1/auth/login", PasswordHandler),
        (r"/api/v1/auth/google", GoogleOAuth2LoginHandler),
        (r"/api/v1/ws", MainWebSocketHandler),
        (r"/icons/(?P<entity_id>[^\/]+)\/(?P<chart_id>[^\/]+)", IconGenerator)
    ]

    application = Application(handlers, **settings)

    server = HTTPServer(application)
    socket = bind_unix_socket("/var/run/elastickube-api.sock", mode=0777)
    server.add_socket(socket)

    IOLoop.current().add_callback(initialize, settings)
开发者ID:carolling,项目名称:elastickube,代码行数:29,代码来源:server.py


示例19: build_webapp_thread

 def build_webapp_thread(self, port=26000):
     app.session = self
     http_server = HTTPServer(WSGIContainer(app))
     http_server.listen(port)
     flask_thread = threading.Thread(target=IOLoop.instance().start)
     flask_thread.daemon = True
     return flask_thread
开发者ID:gitter-badger,项目名称:boofuzz,代码行数:7,代码来源:sessions.py


示例20: inner_run

 def inner_run(self, *args, **options):    
     wsgi_app = WSGIContainer(WSGIHandler())
     tornado_app = Application([(r'/static/(.*)',
         DjangoStaticFilesHandler, {'default_filename': 'none.img'}),
         (r'/media/(.*)', StaticFileHandler, {'path': settings.MEDIA_ROOT}),
         ('/hello-tornado', HelloHandler), 
         ('/ws/doc/(\w+)', DocumentWS), 
         ('.*', FallbackHandler, dict(fallback=wsgi_app))])
     quit_command = (platform == 'win32') and 'CTRL-BREAK' or 'CONTROL-C'
     
     self.stdout.write("Validating models...\n\n")
     self.validate(display_num_errors=True)
     self.stdout.write((
         "%(started_at)s\n"
         "Django version %(version)s, using settings %(settings)r\n"
         "Django tornado server is running at http://%(addr)s:%(port)s/\n"
         "Quit the server with %(quit_command)s.\n"
     ) % {
         "started_at": datetime.now().strftime('%B %d, %Y - %X'),
         "version": self.get_version(),
         "settings": settings.SETTINGS_MODULE,
         "addr": '127.0.0.1',
         "port": self.port,
         "quit_command": quit_command,
     })
     # django.core.management.base forces the locale to en-us. We should
     # set it up correctly for the first request (particularly important
     # in the "--noreload" case).
     translation.activate(settings.LANGUAGE_CODE)
     
     server = HTTPServer(tornado_app)
     server.listen(int(self.port))
     IOLoop.instance().start()
开发者ID:AndreasZitek,项目名称:fiduswriter,代码行数:33,代码来源:runserver.py



注:本文中的tornado.httpserver.HTTPServer类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python httputil.format_timestamp函数代码示例发布时间:2022-05-27
下一篇:
Python httpclient.HTTPRequest类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap