当前位置: 首页>>代码示例>>Python>>正文


Python static.File类代码示例

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


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

示例1: main

def main():
    config = ConfigParser.ConfigParser()
    config.read(os.path.expanduser('~/.b07'))
    api = b07.api.API(reactor,
                      config.get('ingress', 'email'),
                      config.get('ingress', 'password'))
    

    http_root = Redirect('https://localhost:{}/'.format(config.get('server', 'https_port')))
    http_factory = Site(http_root)
    http_endpoint = endpoints.serverFromString(reactor,
                                               'tcp:{}'.format(config.get('server', 'http_port')))
    http_endpoint.listen(http_factory)

    https_root = File(os.path.expanduser(config.get('server', 'web_root')))
    https_root.indexNames = ['index.html']
    https_factory = Site(https_root)
    https_endpoint = endpoints.serverFromString(reactor,
                                                'ssl:{}:privateKey={}:certKey={}'.format(config.get('server', 'https_port'),
                                                                                         os.path.expanduser(config.get('server', 'ssl_key')),
                                                                                         os.path.expanduser(config.get('server', 'ssl_cert'))))
    https_endpoint.listen(https_factory)

    wsfactory = Factory()
    wsfactory.protocol = WebSocketProtocol
    wss_endpoint = endpoints.serverFromString(reactor,
                                              'ssl:{}:privateKey={}:certKey={}'.format(config.get('server', 'wss_port'),
                                                                                       os.path.expanduser(config.get('server', 'ssl_key')),
                                                                                       os.path.expanduser(config.get('server', 'ssl_cert'))))
    wss_endpoint.listen(txws.WebSocketFactory(wsfactory))



    reactor.run()
开发者ID:drhinehart,项目名称:b07bot,代码行数:34,代码来源:server.py

示例2: start

    def start(self):
        """ start websocket server """
        logger.info('start websocket server at %s', self._url)
        self._factory = MyWebSocketServerFactory(
            self._url,
            debug=self._debug
        )

        self._factory.protocol = MyWebSocketServerProtocol
        self._factory.setProtocolOptions(allowHixie76=True)

        self._resource = WebSocketResource(self._factory)

        # we server static files under "/" ..
        root = File('.')

        # and our WebSocket server under "/websocket"
        root.putChild('websocket', self._resource)

        # both under one Twisted Web Site
        site = Site(root)
        site.protocol = HTTPChannelHixie76Aware
        reactor.listenTCP(self._port, site)
        self._thread = threading.Thread(target=reactor.run, args=(False,))
        self._thread.start()
开发者ID:chikuta,项目名称:autobahn_websocketserver_sample,代码行数:25,代码来源:websocket_server_sample.py

示例3: start_web

def start_web(port=8080):
    root = File('./enocean_site')
    root.putChild('radio', RadioResource())
    site = Site(root)
    reactor.listenTCP(port, site)
    logging.info('HTTP server running on port '+str(port))
    return site
开发者ID:jachor,项目名称:enocean-ui,代码行数:7,代码来源:web.py

示例4: download_zip

    def download_zip(self, request, request_id):
        download = yield self.download_database.get_download(
            self.logger, request_id=request_id
        )
        assert download.completed

        self.logger.bind(
            request_id=request_id,
            file_number=download.file_number,
        ).emit("download")

        document_types = yield self.document_types.wait()
        path = download.build_zip(self.jinja_env, self.fernet, document_types)

        request.setHeader(
            "Content-Disposition",
            "attachment; filename={}-eFolder.zip".format(download.file_number)
        )

        resource = File(path, defaultType="application/zip")
        resource.isLeaf = True

        request.notifyFinish().addBoth(lambda *args, **kwargs: os.remove(path))

        returnValue(resource)
开发者ID:department-of-veterans-affairs,项目名称:efolder-express,代码行数:25,代码来源:app.py

示例5: startService

    def startService(self):

        factory = WebSocketServerFactory(u"ws://127.0.0.1:%d" % self.port, debug=self.debug)
        factory.protocol = DispatcherProtocol
        factory.protocol.core = self._core

        # FIXME: Site.start/stopFactory should start/stop factories wrapped as Resources
        factory.startFactory()

        resource = WebSocketResource(factory)

        # we server static files under "/" ..
        webdir = os.path.abspath(pkg_resources.resource_filename("leap.bitmask_core", "web"))
        root = File(webdir)

        # and our WebSocket server under "/ws"
        root.putChild(u"bitmask", resource)

        # both under one Twisted Web Site
        site = Site(root)

        self.site = site
        self.factory = factory

        self.listener = reactor.listenTCP(self.port, site)
开发者ID:ivanalejandro0,项目名称:bitmask_core,代码行数:25,代码来源:websocket.py

示例6: requestAvatar

 def requestAvatar(self, avatarId, mind, *interfaces):
     for iface in interfaces:
         if iface is resource.IResource:
             resc = File("/tmp")
             resc.realm = self
             return (resource.IResource, resc, lambda: None)
     raise NotImplementedError("Can't support that interface.")
开发者ID:DamnWidget,项目名称:backharddi-ng,代码行数:7,代码来源:realm.py

示例7: startService

    def startService(self):

        factory = WebSocketServerFactory(u"ws://127.0.0.1:%d" % self.port)
        factory.protocol = EchoServerProtocol

        # FIXME: Site.start/stopFactory should start/stop factories wrapped as Resources
        factory.startFactory()

        resource = WebSocketResource(factory)

        # we server static files under "/" ..
        webdir = os.path.abspath(pkg_resources.resource_filename("echows", "web"))
        root = File(webdir)

        # and our WebSocket server under "/ws" (note that Twisted uses
        # bytes for URIs)
        root.putChild(b"ws", resource)

        # both under one Twisted Web Site
        site = Site(root)

        self.site = site
        self.factory = factory

        self.listener = reactor.listenTCP(self.port, site)
开发者ID:Anggi-Permana-Harianja,项目名称:autobahn-python,代码行数:25,代码来源:echoservice.py

示例8: __init__

    def __init__(self, pdfpath, cacheroot):
        self.pdf = Pdf(pdfpath)
        self.cacheroot = cacheroot
        if not os.path.exists(cacheroot):
            os.makedirs(cacheroot)

        File.__init__(self, pdfpath)
开发者ID:sdockray,项目名称:looseleaf,代码行数:7,代码来源:pdfserver.py

示例9: setUp

    def setUp(self):
        from twisted.python import threadpool
        reactor.threadpool = threadpool.ThreadPool(0, 10)
        reactor.threadpool.start()

        class Hello(resource.Resource):
            isLeaf = True

            def render_GET(self, request):
                return "<html>Hello, world!</html>"

        self.src_path = tempfile.mkdtemp(suffix=".src")
        self.cache_path = tempfile.mkdtemp(suffix=".cache")
        self._resource = None

        self.createSrcFile("a", "content of a")

        src = File(self.src_path)
        src.putChild("hello", Hello())
        factory = Site(src)
        self.httpserver = reactor.listenTCP(0, factory)
        p = self.httpserver.getHost().port

        plugProps = {"properties": {"cache-size": CACHE_SIZE,
                                    "cache-dir": self.cache_path,
                                    "virtual-hostname": "localhost",
                                    "virtual-port": p}}

        self.plug = \
            file_provider.FileProviderHTTPCachedPlug(plugProps)

        self.stats = DummyStats()
        self.plug.startStatsUpdates(self.stats)

        return self.plug.start(None)
开发者ID:ApsOps,项目名称:flumotion-orig,代码行数:35,代码来源:test_component_httpserver_httpcached_stats.py

示例10: main

def main(argv):
    from twisted.python import log
    from twisted.web.server import Site
    from twisted.web.static import File
    from twisted.internet import reactor
    from twisted.python import log

    observer = log.PythonLoggingObserver('twisted')
    log.startLoggingWithObserver(observer.emit, setStdout=False)

    static_dir = os.path.abspath('.')
    logging.info("registering static folder %r on /" % static_dir)
    root = File(static_dir)

    wr = TwistedWebResource(soap11_application)
    logging.info("registering %r on /%s" % (wr, url))
    root.putChild(url, wr)

    site = Site(root)

    if port[0] == 0:
        port[0] = get_open_port()
    reactor.listenTCP(port[0], site)
    logging.info("listening on: %s:%d" % (host,port))

    return reactor.run()
开发者ID:plq,项目名称:spyne,代码行数:26,代码来源:soap_http_static.py

示例11: startService

    def startService(self):

        factory = WebSocketServerFactory("ws://localhost:%d" % self.port, debug=self.debug)

        factory.protocol = EchoServerProtocol
        factory.setProtocolOptions(allowHixie76=True)  # needed if Hixie76 is to be supported

        # FIXME: Site.start/stopFactory should start/stop factories wrapped as Resources
        factory.startFactory()

        resource = WebSocketResource(factory)

        # we server static files under "/" ..
        webdir = os.path.abspath(pkg_resources.resource_filename("echows", "web"))
        root = File(webdir)

        # and our WebSocket server under "/ws"
        root.putChild("ws", resource)

        # both under one Twisted Web Site
        site = Site(root)
        site.protocol = HTTPChannelHixie76Aware  # needed if Hixie76 is to be supported

        self.site = site
        self.factory = factory

        self.listener = reactor.listenTCP(self.port, site)
开发者ID:Avnerus,项目名称:AutobahnPython,代码行数:27,代码来源:echoservice.py

示例12: makeService

    def makeService(self, options):
        if not options["noisy-logging"]:
            protocol.Factory.noisy = False

        endpoint = twitterEndpoint(options["endpoint"])
        tickeryService = service.MultiService()
        cache = TickeryCache(options["cache-dir"], options["restore-add-queue"], int(options["queue-width"]), endpoint)
        cache.setServiceParent(tickeryService)

        root = File("tickery/www/output")
        root.putChild("tickery", RegularService(cache, endpoint))
        root.putChild(defaults.TICKERY_CALLBACK_CHILD, callback.Callback(cache))

        adminRoot = File("tickery/admin/output")
        adminRoot.putChild("tickery", AdminService(cache))
        root.putChild("admin", adminRoot)

        factory = server.Site(root)
        if options["promiscuous"]:
            kw = {}
        else:
            kw = {"interface": "localhost"}
        tickeryServer = internet.TCPServer(int(options["port"]), factory, **kw)
        tickeryServer.setServiceParent(tickeryService)

        return tickeryService
开发者ID:jkakar,项目名称:Tickery,代码行数:26,代码来源:tickery_service.py

示例13: Insist

class Insist(Resource):
    isLeaf = True

    def __init__(self, cacheloc):
        self.cacheloc = cacheloc
        self.cachefile = None
        if os.path.exists(cacheloc):
            self.cachefile = File(cacheloc)
        self.reqs_waiting = []
        self.started = False
        Resource.__init__(self)

    def render_GET(self, req):
        # Check if someone else has created the file somehow
        if self.cachefile is None and os.path.exists(self.cacheloc):
            self.cachefile = File(self.cacheloc)
        # Check if someone else has *deleted* the file
        elif self.cachefile is not None and not os.path.exists(self.cacheloc):
            self.cachefile = None

        if self.cachefile is not None:
            return self.cachefile.render_GET(req)
        else:
            self.reqs_waiting.append(req)
            req.notifyFinish().addErrback(
                self._nevermind, req)
            if not self.started:
                self.started = True
                reactor.callInThread(self.desist)
            return NOT_DONE_YET

    def _nevermind(self, _err, req):
        self.reqs_waiting.remove(req)

    def desist(self):
        self.serialize_computation(self.cacheloc)
        reactor.callFromThread(self.resist)

    def _get_mime(self):
        return mimetypes.guess_type(self.cacheloc)[0]

    def resist(self):
        if not os.path.exists(self.cacheloc):
            # Error!
            print "%s does not exist - rendering fail!" % (self.cacheloc)
            for req in self.reqs_waiting:
                req.headers["Content-Type"] = "text/plain"
                req.write("cyst error")
                req.finish()
            return

        self.cachefile = File(self.cacheloc)

        # Send content to all interested parties
        for req in self.reqs_waiting:
            self.cachefile.render(req)

    def serialize_computation(self, outpath):
        raise NotImplemented
开发者ID:EnGassa,项目名称:gentle,代码行数:59,代码来源:cyst.py

示例14: __init__

 def __init__(self, feederName, lockCamera, lockSensor):
     threading.Thread.__init__(self)
     feederName = feederName
     res = File('/home/pi/PiFeed/src/')
     res.putChild('', res)
     factory = Site(res)
     reactor.listenTCP(8000, factory)
     print('%s: twisted web server started' % (feederName))
开发者ID:zergler,项目名称:pifeed,代码行数:8,代码来源:infoServer.py

示例15: getChild

 def getChild(self, path, request):
    resource = File.getChild(self, path, request)
    for pat, repl in self._virtualLinks.iteritems():
       newPath = pat.sub(repl, path)
       if newPath != path:
          resource = File.getChild(self, newPath, request)
          break
    return resource
开发者ID:istobran,项目名称:eaEmu,代码行数:8,代码来源:webServices.py


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