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

Python cherrypyserver.WebSocketPlugin类代码示例

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

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



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

示例1: run

    def run(self):
        log.info("starting on port {}".format(port))
        plugin = WebSocketPlugin(cherrypy.engine)
        plugin.subscribe()
        cherrypy.tools.websocket = WebSocketTool()

        p.events.on("switch", self.dispatch_device, priority=True)
        p.events.on("coil", self.dispatch_device, priority=True)
        p.events.on("lamp", self.dispatch_device, priority=True)
        p.events.on("flasher", self.dispatch_device, priority=True)
        p.events.on("gi", self.dispatch_device, priority=True)
        p.events.on("notice", self.dispatch_notice, priority=True)

        cherrypy.quickstart(Root(), "/", config={
            "/": {
                "tools.staticdir.on": True,
                "tools.staticdir.root": os.path.abspath(os.path.join(
                        os.path.dirname(__file__), "..", "..", "web")),
                "tools.staticdir.index": "index.html",
                "tools.staticdir.dir": ""
            },
            "/console": {
                "tools.staticdir.on": True,
                "tools.staticdir.dir": "console"
            },
            "/ws": {
                "tools.websocket.on": True,
                "tools.websocket.handler_cls": WebSocketHandler
            }
        })
        self.done(plugin)
开发者ID:town-hall-pinball,项目名称:project-omega,代码行数:31,代码来源:server.py


示例2: stop

 def stop(self):
     WebSocketPlugin.stop(self)
     self.bus.unsubscribe('add-client', self.add_client)
     self.bus.unsubscribe('get-client', self.get_client)
     self.bus.unsubscribe('del-client', self.del_client)
     self.bus.unsubscribe('get_main-client', self.get_main_client_num)
     self.bus.unsubscribe('switch-state', self.switch_state)
开发者ID:lis-epfl,项目名称:DRIC,代码行数:7,代码来源:server.py


示例3: __init__

    def __init__(self, bus):
        try:
            import wsaccel
            wsaccel.patch_ws4py()
        except ImportError:
            # wsaccel isn't a requirement. also, this occurs when docs are
            # built on readthedocs.org
            pass

        BaseWebSocketPlugin.__init__(self, bus)
开发者ID:opmuse,项目名称:opmuse,代码行数:10,代码来源:ws.py


示例4: extend_server_configuration

 def extend_server_configuration(cls, engine, config):
     """Extend the server configuration."""
     cp_plugin = WebSocketPlugin(engine)
     cp_plugin.subscribe()
     cherrypy.tools.websocket = WebSocketTool()
     for handler in cls.handlers:
         config.update({
             handler.ws_point: {
                 'tools.websocket.on': True,
                 'tools.websocket.handler_cls': handler,
             },
         })
开发者ID:v-legoff,项目名称:pa-poc3,代码行数:12,代码来源:plugin.py


示例5: __init__

    def __init__(self, bus):
        """
        This plugin is the board controller. It keeps
        track of all boards and their registered participants.

        You may access the global instance of this plugin
        through the `bus.websockets` attribute.
        """
        WebSocketPlugin.__init__(self, bus)

        # every 30s, we check if we have dead boards
        # and we clean them
        plugins.Monitor(bus, self.drop_dead_boards, 30).subscribe()
    
        # board index to quickly retrieve
        # clients of a given board
        self.boards = {}
开发者ID:B-Rich,项目名称:WebSocket-for-Python,代码行数:17,代码来源:app.py


示例6: start_cherrypy_debug_server

def start_cherrypy_debug_server(htdocs_path,
                                http_host, http_port,
                                mpd_host, mpd_port=6600, mpd_password=None):

    # set cherrypy configuration.
    cherrypy.config.update({'server.socket_port': http_port})
    cherrypy.config.update({'server.socket_host': http_host})

    if (not os.path.isdir(htdocs_path)):
        print("=" * 80 + """
  The ympd htdocs dir is not available: perhaps the git submodule is missing?
""" + "=" * 80)
        sys.exit(1)

    # Add the websocket requirements.
    a = WebSocketPlugin(cherrypy.engine)
    a.manager = WebSocketManager()
    a.subscribe()
    cherrypy.tools.websocket = WebSocketTool()


    web_root = Root()

    # get a function to instantiate the websocket with the correct settings.
    ympd_websocket = ympdWebSocket_wrap(mpd_host, mpd_port, mpd_password)

    # Run a no-websocket alternative at http://hostname:port/nows/
    nowebsocket = ympdNoWebSocket_wrap(mpd_host, mpd_port, mpd_password)
    web_root.nows = nowebsocket(htdocs_path)
    # this implementation uses POST requests communicate.
    # Takes a little bit longer for the UI to update, but it should get through
    # firewalls and proxies where the websocket cannot.

    cherrypy.quickstart(web_root, '/', config={
                '/ws': {'tools.websocket.on': True,
                        'tools.websocket.handler_cls': ympd_websocket},
                '/': {'tools.staticdir.on': True,
                      'tools.staticdir.dir': os.path.join(htdocs_path),
                      "tools.staticdir.index": "index.html"},
            }
            )
开发者ID:iwanders,项目名称:ympd_python,代码行数:41,代码来源:cherry.py


示例7: _configure_server

def _configure_server(restarting=False):
    global websocket_plugin

    # Configure server error log
    cherrypy.config.update({'log.error_file': 'cherrypy.error.log'})

    # Configure server url
    cherrypy.config.update({'server.socket_host': s2n(autosubliminal.WEBSERVERIP),
                            'server.socket_port': int(autosubliminal.WEBSERVERPORT)
                            })

    # Disable engine plugins (no need for autoreload plugin)
    cherrypy.config.update({'engine.autoreload.on': False})

    # Read and store cherrypy server version (if not set, it returns CherryPy/Unknown because it's not installed)
    server_header = 'CherryPy/%s' % get_library_version('cherrypy')
    cherrypy.config.update({'response.headers.server': server_header})

    # Configure authentication in if a username and password is set by the user
    if autosubliminal.USERNAME and autosubliminal.PASSWORD:
        users = {s2n(autosubliminal.USERNAME): s2n(autosubliminal.PASSWORD)}
        cherrypy.config.update({'tools.auth_digest.on': True,
                                'tools.auth_digest.realm': 'Auto-Subliminal website',
                                'tools.auth_digest.get_ha1': auth_digest.get_ha1_dict_plain(users),
                                'tools.auth_digest.key': 'yek.tsegid_htua.lanimilbuS-otuA'  # Can be any random string
                                })

    # Configure our custom json_out_handler (Uncomment if it should be used for any @cherrypy.tools.json_out())
    # cherrypy.config.update({'tools.json_out.handler': json_out_handler})

    if not restarting:
        # Enable websocket plugin
        websocket_plugin = WebSocketPlugin(cherrypy.engine)
        websocket_plugin.subscribe()
        cherrypy.tools.websocket = WebSocketTool()
    else:
        # When restarting we need to create a new websocket manager thread (you cannot start the same thread twice!)
        websocket_plugin.manager = WebSocketManager()
        # When restarting we need to clear the httpserver to force the creation of a new one (needed for ip/port change)
        cherrypy.server.httpserver = None
开发者ID:h3llrais3r,项目名称:Auto-Subliminal,代码行数:40,代码来源:application.py


示例8: start

    def start(self):
        """
        Start the server. This blocks
        """

        # Setting up plugins
        pluginmanager.load_models()
        pluginmanager.load_plugin_roots(self)
        create_tables()

        self.wsplugin = WebSocketPlugin(cherrypy.engine)
        self.wsplugin.subscribe()
        cherrypy.tools.websocket = WebSocketTool()

        # cherrypy.config.update({"log.access_file": "access.log",
        #                         "log.error_file": "error.log"})

        cherrypy.engine.subscribe("receive", self.receive)

        self.start_updater()

        config = {"/ws": {"tools.websocket.on": True, "tools.websocket.handler_cls": WebSocketHandler}}
        cherrypy.quickstart(self, "/", config=config)
开发者ID:ibutra,项目名称:SpyDashServer,代码行数:23,代码来源:server.py


示例9: start

 def start(self):
     self.log.debug("ZuulWeb starting")
     self.stream_manager.start()
     self.wsplugin = WebSocketPlugin(cherrypy.engine)
     self.wsplugin.subscribe()
     cherrypy.engine.start()
开发者ID:,项目名称:,代码行数:6,代码来源:


示例10: default

    @cherrypy.expose
    def default(self):
        pass


class WebSocketChecker(WebSocketTool):
    def __init__(self):
        cherrypy.Tool.__init__(self, "before_handler", self.upgrade)

    def upgrade(self, **kwargs):
        try:
            kwargs["handler_cls"].check_authentication()
        except:
            raise cherrypy.HTTPError(401, "You must be logged in to establish a websocket connection.")
        else:
            return WebSocketTool.upgrade(self, **kwargs)


cherrypy.tools.websockets = WebSocketChecker()

websocket_plugin = WebSocketPlugin(cherrypy.engine)
websocket_plugin.subscribe()

broadcaster = Caller(WebSocketDispatcher.broadcast)
responder = Caller(WebSocketDispatcher.handle_message, threads=config['ws_thread_pool'])

cherrypy.engine.subscribe("stop", WebSocketDispatcher.close_all)
for _task in [broadcaster, responder]:
    cherrypy.engine.subscribe("start", _task.start, priority=99)
    cherrypy.engine.subscribe("stop", _task.stop)
开发者ID:ftobia,项目名称:sideboard,代码行数:30,代码来源:websockets.py


示例11: stop

 def stop(self):
     self.bus.unsubscribe('websocket-message', self.message)
     WebSocketPlugin.stop(self)
开发者ID:bharling,项目名称:Text-Adventure-Programming-Language,代码行数:3,代码来源:taple_host.py


示例12: __init__

 def __init__(self, bus):
     WebSocketPlugin.__init__(self, bus)
开发者ID:bharling,项目名称:Text-Adventure-Programming-Language,代码行数:2,代码来源:taple_host.py


示例13: print

    ch.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(name)s - %(asctime)s - %(levelname)s'
                                  ' - %(message)s')
    ch.setFormatter(formatter)
    interface_logger.addHandler(ch)

    # create the preset folder if it does not exist:
    preset_dir = os.path.abspath(args.presetdir)
    if (not os.path.isdir(preset_dir)):
        print("Preset folder {} did not exist, creating.".format(preset_dir))
        os.makedirs(preset_dir)

    # Add the websocket requirements.
    cherrypy.tools.websocket = WebSocketTool()

    a = WebSocketPlugin(cherrypy.engine)
    a.manager = WebSocketManager()
    a.subscribe()

    stack_interface = interface.StackInterface()
    stack_interface.daemon = True
    stack_interface.start()
    server_tree = FocusStackRoot(stack_interface, preset_dir=preset_dir)

    # create a broadcast function which relays messages received over the
    # serial port to the websockets via the websocketmanager.
    def broadcaster():
        m = stack_interface.get_message()
        if m:
            payload = dict(m)
            payload["msg_type"] = message.msg_type_name[payload["msg_type"]]
开发者ID:iwanders,项目名称:focus_stacking,代码行数:31,代码来源:server.py


示例14: __init__

 def __init__(self, bus):
     WebSocketPlugin.__init__(self, bus)
     self.clients = {}
开发者ID:AlexSnet,项目名称:oneline,代码行数:3,代码来源:ol.py


示例15: stop

 def stop(self):
     WebSocketPlugin.stop(self)
     self.bus.unsubscribe("add", self.add)
     self.bus.unsubscribe("get", self.get)
     self.bus.unsubscribe("remove", self.remove)
开发者ID:simonbroggi,项目名称:SchneeEulen,代码行数:5,代码来源:snowly-master.py


示例16: ZuulWeb


#.........这里部分代码省略.........
        route_map.connect('api', '/api/info',
                          controller=api, action='info')
        route_map.connect('api', '/api/connections',
                          controller=api, action='connections')
        route_map.connect('api', '/api/tenants',
                          controller=api, action='tenants')
        route_map.connect('api', '/api/tenant/{tenant}/info',
                          controller=api, action='tenant_info')
        route_map.connect('api', '/api/tenant/{tenant}/status',
                          controller=api, action='status')
        route_map.connect('api', '/api/tenant/{tenant}/status/change/{change}',
                          controller=api, action='status_change')
        route_map.connect('api', '/api/tenant/{tenant}/jobs',
                          controller=api, action='jobs')
        route_map.connect('api', '/api/tenant/{tenant}/job/{job_name}',
                          controller=api, action='job')
        route_map.connect('api', '/api/tenant/{tenant}/projects',
                          controller=api, action='projects')
        route_map.connect('api', '/api/tenant/{tenant}/project/{project:.*}',
                          controller=api, action='project')
        route_map.connect(
            'api',
            '/api/tenant/{tenant}/pipeline/{pipeline}'
            '/project/{project:.*}/branch/{branch:.*}/freeze-jobs',
            controller=api, action='project_freeze_jobs'
        )
        route_map.connect('api', '/api/tenant/{tenant}/pipelines',
                          controller=api, action='pipelines')
        route_map.connect('api', '/api/tenant/{tenant}/labels',
                          controller=api, action='labels')
        route_map.connect('api', '/api/tenant/{tenant}/nodes',
                          controller=api, action='nodes')
        route_map.connect('api', '/api/tenant/{tenant}/key/{project:.*}.pub',
                          controller=api, action='key')
        route_map.connect('api', '/api/tenant/{tenant}/'
                          'project-ssh-key/{project:.*}.pub',
                          controller=api, action='project_ssh_key')
        route_map.connect('api', '/api/tenant/{tenant}/console-stream',
                          controller=api, action='console_stream')
        route_map.connect('api', '/api/tenant/{tenant}/builds',
                          controller=api, action='builds')
        route_map.connect('api', '/api/tenant/{tenant}/build/{uuid}',
                          controller=api, action='build')
        route_map.connect('api', '/api/tenant/{tenant}/buildsets',
                          controller=api, action='buildsets')
        route_map.connect('api', '/api/tenant/{tenant}/buildset/{uuid}',
                          controller=api, action='buildset')
        route_map.connect('api', '/api/tenant/{tenant}/config-errors',
                          controller=api, action='config_errors')

        for connection in connections.connections.values():
            controller = connection.getWebController(self)
            if controller:
                cherrypy.tree.mount(
                    controller,
                    '/api/connection/%s' % connection.connection_name)

        # Add fallthrough routes at the end for the static html/js files
        route_map.connect(
            'root_static', '/{path:.*}',
            controller=StaticHandler(self.static_path),
            action='default')

        conf = {
            '/': {
                'request.dispatch': route_map
            }
        }
        cherrypy.config.update({
            'global': {
                'environment': 'production',
                'server.socket_host': listen_address,
                'server.socket_port': int(listen_port),
            },
        })

        cherrypy.tree.mount(api, '/', config=conf)

    @property
    def port(self):
        return cherrypy.server.bound_addr[1]

    def start(self):
        self.log.debug("ZuulWeb starting")
        self.stream_manager.start()
        self.wsplugin = WebSocketPlugin(cherrypy.engine)
        self.wsplugin.subscribe()
        cherrypy.engine.start()

    def stop(self):
        self.log.debug("ZuulWeb stopping")
        self.rpc.shutdown()
        cherrypy.engine.exit()
        # Not strictly necessary, but without this, if the server is
        # started again (e.g., in the unit tests) it will reuse the
        # same host/port settings.
        cherrypy.server.httpserver = None
        self.wsplugin.unsubscribe()
        self.stream_manager.stop()
        self.zk.disconnect()
开发者ID:,项目名称:,代码行数:101,代码来源:


示例17: __init__

 def __init__(self, bus):
     WebSocketPlugin.__init__(self, bus)
     self.clients = []
     self.history = []
     self.history_size = HISTORY_SIZE
开发者ID:DeForce,项目名称:multichat_python,代码行数:5,代码来源:webchat.py


示例18: __init__

 def __init__(self, bus):
     WebSocketPlugin.__init__(self, bus)
     self.clients = {}
     self.main_client_code = -1
开发者ID:lis-epfl,项目名称:DRIC,代码行数:4,代码来源:server.py


示例19: start

 def start(self):
     WebSocketPlugin.start(self)
     self.bus.subscribe('add-client', self.add_client)
     self.bus.subscribe('del-client', self.del_client)
     self.bus.subscribe('add-history', self.add_history)
     self.bus.subscribe('get-history', self.get_history)
开发者ID:DeForce,项目名称:multichat_python,代码行数:6,代码来源:webchat.py


示例20: start_broker


#.........这里部分代码省略.........
        # http://api.mongodb.org/python/current/examples/authentication.html
        _client = MongoClient("mongodb://" + _user + ":" + _password + "@" + _host)
    else:
        write_srvc_dbg("===Connecting to local MongoDB backend===")
        _client = MongoClient()

    _database_name = settings.get("broker/database/databaseName", _default="optimalframework")
    write_srvc_dbg("Using database name :" + _database_name)

    _database = _client[_database_name]
    database_access = DatabaseAccess(_database=_database, _schema_tools=schema_tools)
    of.common.logging.callback = log_to_database
    database_access.save(store_process_system_document(_process_id=process_id,
                                                       _name="Broker instance(" + address + ")"),
                         _user=None,
                         _allow_save_id=True)
    plugins.call_hook("after_db_connect", _broker_scope=globals())
    # TODO: It is possible that one would like to initialize, or at least read the plugins *before* trying to connect to the database

    # Must have a valid CherryPy version
    if hasattr(cherrypy.engine, "subscribe"):  # CherryPy >= 3.1
        pass
    else:
        write_to_log(_data="This application requires CherryPy >= 3.1 or higher.", _category=EC_SERVICE,
                     _severity=SEV_FATAL)
        raise Exception("Broker init: This application requires CherryPy >= 3.1 or higher.")
        # cherrypy.engine.on_stop_engine_list.append(_save_data)

    def ssl_path():
        # Figure out the path to the ssl-certificates
        # TODO: Load from database instead. Or not? (PROD-19)
        return os.path.dirname(_cfg_filename)

    # Initialize CherryPy:s global configuration; note that this could be moved into a configuration file
    cherrypy.config.update({
        "tools.encode.on": True,
        "tools.encode.encoding": "utf-8",
        "tools.decode.on": True,
        "tools.trailing_slash.on": True,
        "tools.staticdir.root": os.path.abspath(os.path.dirname(__file__)),
        "server.ssl_module": "builtin",
        # TODO: Remove this when this bug is fixed:
        # https://bitbucket.org/cherrypy/cherrypy/issue/1341/autoreloader-also-fails-if-six-is-present
        "engine.autoreload.on": False,
        'server.socket_host': '0.0.0.0',
        "server.ssl_certificate": os.path.join(ssl_path(), "optimalframework_test_cert.pem"),
        "server.ssl_private_key": os.path.join(ssl_path(), "optimalframework_test_privkey.pem"),
        "error_page.default": error_message_default
    })
    write_srvc_dbg("Starting CherryPy, ssl at " + os.path.join(ssl_path(), "optimalframework_test_privkey.pem"))

    web_config = {
        # The UI root
        "/": {
            "tools.staticdir.on": True,
            "tools.staticdir.dir": "ui",
            "tools.trailing_slash.on": True,
            "tools.staticdir.index": "index.html",
        },
        # Note that the web socket handling is put under /socket.
        "/socket": {
            "tools.websocket.on": True,
            "tools.websocket.handler_cls": BrokerWebSocket
        }
    }

    global web_root

    cherrypy._global_conf_alias.update(web_config)
    web_socket_plugin = WebSocketPlugin(cherrypy.engine)
    web_socket_plugin.subscribe()
    cherrypy.tools.websocket = WebSocketTool()

    cherrypy.engine.signals.bus.signal_handler.handlers = {'SIGUSR1': cherrypy.engine.signals.bus.graceful}

    # Initialize the decorator-based authentication framework
    init_authentication(MongoDBAuthBackend(database_access))

    # Initialize root UI
    web_root = CherryPyBroker(_process_id=process_id, _address=address, _database_access=database_access)
    # Initialize messaging
    of.common.messaging.websocket.monitor = Monitor(_handler=BrokerWebSocketHandler(process_id, _peers=web_root.peers,
                                                                                    _database_access=database_access,
                                                                                    _schema_tools=database_access.schema_tools,
                                                                                    _address=address))

    web_root.plugins = plugins
    # Generate the static content, initialisation
    plugins.call_hook("init_web", _broker_scope = globals())

    _web_config_debug = "Broker configured. Starting web server. Web config:\n"
    for _curr_key, _curr_config in web_config.items():
        if "tools.staticdir.dir" in _curr_config:
            _web_config_debug += "Path: " + _curr_key + " directory: " + _curr_config["tools.staticdir.dir"]
        else:
            _web_config_debug += "Path: " + _curr_key + " - no static dir"

    write_to_log(_web_config_debug, _category=EC_SERVICE, _severity=SEV_INFO)
    plugins.call_hook("pre_webserver_start", web_config=web_config, globals=globals())
    cherrypy.quickstart(web_root, "/", web_config)
开发者ID:OptimalBPM,项目名称:of,代码行数:101,代码来源:broker.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python streaming.Stream类代码示例发布时间:2022-05-26
下一篇:
Python manager.WebSocketManager类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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