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

Python resource.Resource类代码示例

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

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



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

示例1: bravo_site

def bravo_site(services):
    # extract worlds and non-world services only once at startup
    worlds = {}
    other_services = {}
    for name, service in services.iteritems():
        factory = service.args[1]
        if isinstance(factory, BravoFactory):
            worlds[factory.name] = factory
        else:
            # XXX: do we really need those ?
            other_services[name] = factory
    # add site root
    root = Resource()
    root.putChild('', BravoResource(BravoRootElement(worlds, other_services)))
    # add world sub pages and related plugins
    for world, factory in worlds.iteritems():
        # Discover parameterized plugins.
        plugins = retrieve_plugins(IWorldResource,
                                   parameters={"factory": factory})
        # add sub page
        child = BravoResource(BravoWorldElement(factory, plugins), False)
        root.putChild(world, child)
        # add plugins
        for name, resource in plugins.iteritems():
            # add plugin page
            child.putChild(name, resource)
    # create site
    site = Site(root)
    return site
开发者ID:RedKrieg,项目名称:bravo,代码行数:29,代码来源:web.py


示例2: __init__

    def __init__(self, host, port, path, path_rewrite=None, reactor=reactor,
                 tls=False, headers={}):
        """
        @param host: the host of the web server to proxy.
        @type host: C{str}

        @param port: the port of the web server to proxy.
        @type port: C{port}

        @param path: the base path to fetch data from. Note that you shouldn't
            put any trailing slashes in it, it will be added automatically in
            request. For example, if you put B{/foo}, a request on B{/bar} will
            be proxied to B{/foo/bar}.  Any required encoding of special
            characters (such as " " or "/") should have been done already.

        @param path_rewrite: list of lists with two regexp strings
        used for rewriting the path.

        @param tls: use tls or not

        @type path: C{str}
        """
        Resource.__init__(self)
        self.host = host
        self.port = port
        self.path = path
        self.path_rewrite = path_rewrite
        self.tls = tls
        self.reactor = reactor
        self.headers = headers
开发者ID:SUNET,项目名称:lobber-deluge-core,代码行数:30,代码来源:proxy.py


示例3: XMLRPCService

class XMLRPCService(server.Site):

    def __init__(self, port=None):
        self._port = port or get_random_port()
        self._addrs = []
        self._root = Resource()
        self._root.putChild('XMLRPC', XMLRPCResource(self._root))
        server.Site.__init__(self, self._root)

    def log(self, request):
        log.info('%s http://localhost:%d%s' % (request.method,
                                               self._port,
                                               request.uri))

    @property
    def port(self):
        return self._port

    def serve(self):
        log.info('Listening on port %d' % (self._port, ))
        reactor.listenTCP(self._port, self)

    def is_active(self):
        return len(self._addrs)

    def stop(self):
        self._service.stopFactory()
开发者ID:EasyDevSolutions,项目名称:stoq,代码行数:27,代码来源:xmlrpcservice.py


示例4: _testRender

    def _testRender(self, uri, expectedURI):
        """
        Check that a request pointing at C{uri} produce a new proxy connection,
        with the path of this request pointing at C{expectedURI}.
        """
        root = Resource()
        reactor = MemoryReactor()
        resource = ReverseProxyResource("127.0.0.1", 1234, "/path", reactor)
        root.putChild("index", resource)
        site = Site(root)

        transport = StringTransportWithDisconnection()
        channel = site.buildProtocol(None)
        channel.makeConnection(transport)
        # Clear the timeout if the tests failed
        self.addCleanup(channel.connectionLost, None)

        channel.dataReceived("GET %s HTTP/1.1\r\nAccept: text/html\r\n\r\n" % (uri,))

        # Check that one connection has been created, to the good host/port
        self.assertEquals(len(reactor.tcpClients), 1)
        self.assertEquals(reactor.tcpClients[0][0], "127.0.0.1")
        self.assertEquals(reactor.tcpClients[0][1], 1234)

        # Check the factory passed to the connect, and its given path
        factory = reactor.tcpClients[0][2]
        self.assertIsInstance(factory, ProxyClientFactory)
        self.assertEquals(factory.rest, expectedURI)
        self.assertEquals(factory.headers["host"], "127.0.0.1:1234")
开发者ID:twonds,项目名称:twisted,代码行数:29,代码来源:test_proxy.py


示例5: __init__

 def __init__(self, out=None, *a, **kw):
     Resource.__init__(self, *a, **kw)
     self._log = logging.getLogger(self.__class__.__name__)
     self._log.debug('Initialized.')
     if out is None:
         out = sys.stdout
     self.out = out
开发者ID:ArtRichards,项目名称:leastauthority.com,代码行数:7,代码来源:devpay_complete.py


示例6: __init__

 def __init__(self, config, port=None):
     super(IdentityServer, self).__init__(config)
     self.plugin_mapping = config["plugin_mapping"]
     self.setupMySQL(config)
     self.setupIdentityQueue(config)
     self.cassandra_cf_identity = config["cassandra_cf_identity"]
     self.cassandra_cf_connections = config["cassandra_cf_connections"]
     self.cassandra_cf_recommendations = config["cassandra_cf_recommendations"]
     self.cassandra_cf_reverse_recommendations = config["cassandra_cf_reverse_recommendations"]
     self.cassandra_client = CassandraClusterPool(
         config["cassandra_servers"],
         keyspace=config["cassandra_keyspace"],
         pool_size=len(config["cassandra_servers"]) * 2)
     self.cassandra_client.startService()
     resource = Resource()
     self.function_resource = Resource()
     resource.putChild("function", self.function_resource)
     if port is None:
         port = config["identity_server_port"]
     self.site_port = reactor.listenTCP(port, server.Site(resource))
     self.expose(self.updateConnections)
     self.expose(self.updateAllConnections)
     self.expose(self.updateAllIdentities)
     self.expose(self.getRecommendations)
     self.expose(self.getReverseRecommendations)
     self.expose(self.updateIdentity)
     # setup manhole
     manhole_namespace = {
         'service': self,
         'globals': globals(),
     }
     reactor.listenTCP(config["manhole_identity_port"], self.getManholeFactory(manhole_namespace, admin=config["manhole_password"]))
开发者ID:hiidef,项目名称:hiispider,代码行数:32,代码来源:identity.py


示例7: test_posted

    def test_posted(self):
        root = Resource()
        collector = Collector()
        root.putChild(b"foo", collector)

        from twisted.internet import reactor
        while True:
            try:
                port = reactor.listenTCP(0, Site(root))
            except:
                pass
            else:
                self.addCleanup(port.stopListening)
                port_number = port.getHost().port
                break

        fluentd_url = URL(
            scheme="http",
            host="127.0.0.1",
            port=port_number,
            path=["foo"],
        )

        agent = Agent(reactor)
        destination = FluentdDestination(agent, fluentd_url)
        destination({"hello": "world"})

        def check():
            self.assertEquals(collector.collected, [b'json={"hello": "world"}'])

        return deferLater(reactor, 0.1, check)
开发者ID:LeastAuthority,项目名称:leastauthority.com,代码行数:31,代码来源:test_eliot_destination.py


示例8: __init__

    def __init__(self, app, chunked=False, max_content_length=2 * 1024 * 1024,
                                           block_length=8 * 1024):
        Resource.__init__(self)

        self.http_transport = TwistedHttpTransport(app, chunked,
                                            max_content_length, block_length)
        self._wsdl = None
开发者ID:amgibson,项目名称:spyne,代码行数:7,代码来源:twisted.py


示例9: create_web_service

def create_web_service(trompet, config):
    "Creates the web service. Returns a tuple (service, site)."
    site = Resource()
    trompet.web = site
    site.putChild("", Root())
    service = internet.TCPServer(config["web"]["port"], server.Site(site))
    service.setServiceParent(trompet)
开发者ID:RonnyPfannschmidt,项目名称:trompet,代码行数:7,代码来源:web.py


示例10: run_twisted

def run_twisted(apps, port, static_dir='.'):
    """Twisted wrapper for the rpclib.server.wsgi.Application

    Takes a list of tuples containing application, url pairs, and a port to
    to listen to.
    """

    if static_dir != None:
        static_dir = os.path.abspath(static_dir)
        logging.info("registering static folder %r on /" % static_dir)
        root = twisted.web.static.File(static_dir)
    else:
        root = Resource()

    for app, url in apps:
        resource = WSGIResource(reactor, reactor, app)
        logging.info("registering %r on /%s" % (app, url))
        root.putChild(url, resource)

    site = twisted.web.server.Site(root)

    reactor.listenTCP(port, site)
    logging.info("listening on: 0.0.0.0:%d" % port)

    return reactor.run()
开发者ID:mardiros,项目名称:rpclib,代码行数:25,代码来源:wsgi_wrapper.py


示例11: __init__

 def __init__(self, cashier):
     """
     :param cashier: The cashier we talk to
     """
     Resource.__init__(self)
     self.cashier = cashier
     self.compropago = cashier.compropago
开发者ID:ysobolev,项目名称:sputnik,代码行数:7,代码来源:cashier.py


示例12: __init__

 def __init__(self, parent):
    """
    """
    Resource.__init__(self)
    self._parent = parent
    self._debug = self._parent._debug
    self.reactor = self._parent.reactor
开发者ID:PlutoniumHeart,项目名称:VTK,代码行数:7,代码来源:http.py


示例13: run_server

def run_server(fd=None, port=None, procs=None, verbose=False):
    if args.verbose:
        log.startLogging(stdout)
        environ['SOLEDAD_LOG_TO_STDOUT'] = '1'

    config = get_config()
    path = config["blobs_path"]
    if not port:
        port = int(config["blobs_port"])

    root = Resource()
    root.putChild('blobs', BlobsResource("filesystem", path))
    factory = Site(root)

    if fd is None:
        # Create a new listening port and several other
        # processes to help out.
        if procs is None:
            procs = cpu_count()
        log.msg('A total of %d processes will listen on port %d.' % (procs, port))
        port = reactor.listenTCP(port, factory)
        for i in range(procs - 1):
            reactor.spawnProcess(
                None, executable, [executable, __file__, str(port.fileno())],
                childFDs={0: 0, 1: 1, 2: 2, port.fileno(): port.fileno()},
                env=environ)
    else:
        # Another process created the port, just start listening on it.
        log.msg('Adopting file descriptor %d...' % fd)
        port = reactor.adoptStreamPort(fd, AF_INET, factory)

    reactor.run()
开发者ID:leapcode,项目名称:soledad-perf,代码行数:32,代码来源:blobs-server.py


示例14: startService

    def startService(self):
        app = self._prov_service.app
        dhcp_request_processing_service = self._dhcp_process_service.dhcp_request_processing_service
        if self._config['general.rest_authentication']:
            credentials = (self._config['general.rest_username'],
                           self._config['general.rest_password'])
            server_resource = new_restricted_server_resource(app, dhcp_request_processing_service, credentials)
            logger.info('Authentication is required for REST API')
        else:
            server_resource = new_server_resource(app, dhcp_request_processing_service)
            logger.warning('No authentication is required for REST API')
        root_resource = Resource()
        root_resource.putChild('provd', server_resource)
        rest_site = Site(root_resource)

        port = self._config['general.rest_port']
        interface = self._config['general.rest_ip']
        if interface == '*':
            interface = ''
        logger.info('Binding HTTP REST API service to "%s:%s"', interface, port)
        if self._config['general.rest_ssl']:
            logger.info('SSL enabled for REST API')
            context_factory = ssl.DefaultOpenSSLContextFactory(self._config['general.rest_ssl_keyfile'],
                                                               self._config['general.rest_ssl_certfile'])
            self._tcp_server = internet.SSLServer(port, rest_site, context_factory, interface=interface)
        else:
            self._tcp_server = internet.TCPServer(port, rest_site, interface=interface)
        self._tcp_server.startService()
        Service.startService(self)
开发者ID:Eyepea,项目名称:xivo-skaro,代码行数:29,代码来源:main.py


示例15: build_resource

def build_resource():
    root = Resource()

    for key, val in RESOURCE_MAPPING.iteritems():
        root.putChild(key, val)

    return root
开发者ID:rockstar,项目名称:AtlasThunder,代码行数:7,代码来源:resources.py


示例16: __init__

 def __init__(self, logDirResource, allowedChannels=None):
     Resource.__init__(self)
     self.logDirResource = logDirResource
     allowed = allowedChannels
     if allowed is not None:
         allowed = set(unprefixedChannel(channel) for channel in allowedChannels)
     self.allowed = allowed
开发者ID:Weasyl,项目名称:elastirc,代码行数:7,代码来源:elastirc.py


示例17: _put_plugin_resources

def _put_plugin_resources(client_resource):
    # Plugin resources and plugin info
    load_list_css = []
    load_list_js = []
    mode_table = {}
    plugin_resources = Resource()
    client_resource.putChild('plugins', plugin_resources)
    for resource_def in getPlugins(IClientResourceDef, shinysdr.plugins):
        # Add the plugin's resource to static serving
        plugin_resources.putChild(resource_def.key, resource_def.resource)
        plugin_resource_url = '/client/plugins/' + urllib.quote(resource_def.key, safe='') + '/'
        # Tell the client to load the plugins
        # TODO constrain path values to be relative (not on a different origin, to not leak urls)
        if resource_def.load_css_path is not None:
            load_list_css.append(plugin_resource_url + resource_def.load_cs_path)
        if resource_def.load_js_path is not None:
            # TODO constrain value to be in the directory
            load_list_js.append(plugin_resource_url + resource_def.load_js_path)
    for mode_def in get_modes():
        mode_table[mode_def.mode] = {
            u'info_enum_row': mode_def.info.to_json(),
            u'can_transmit': mode_def.mod_class is not None
        }
    # Client gets info about plugins through this resource
    client_resource.putChild('plugin-index.json', static.Data(serialize({
        u'css': load_list_css,
        u'js': load_list_js,
        u'modes': mode_table,
    }).encode('utf-8'), 'application/json'))
开发者ID:bitglue,项目名称:shinysdr,代码行数:29,代码来源:app.py


示例18: __init__

 def __init__(self, source):
     """
     @param source: The NotificationSource to fetch notifications from.
     """
     Resource.__init__(self)
     self.source = source
     self._finished = {}
开发者ID:CanonicalLtd,项目名称:txlongpoll,代码行数:7,代码来源:frontend.py


示例19: __init__

 def __init__(self):
     Resource.__init__(self)
     self.putChild("status", Status())
     self.putChild("follow", Follow())
     self.putChild("delay", Delay())
     self.putChild("partial", Partial())
     self.putChild("drop", Drop())
开发者ID:5n1p,项目名称:scrapy,代码行数:7,代码来源:mockserver.py


示例20: __init__

 def __init__(self, debug=False, signing_key=None, signing_id=None,
              event_handler=GenericEventHandler):
     Resource.__init__(self)
     self.signing_key = signing_key
     self.signing_id = signing_id
     self.debug = debug # This class acts as a 'factory', debug is used by Protocol
     self.event_handler = event_handler
开发者ID:300184,项目名称:eth-stratum-mining-proxy,代码行数:7,代码来源:http_transport.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python server.Request类代码示例发布时间:2022-05-27
下一篇:
Python resource.NoResource类代码示例发布时间: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