本文整理汇总了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()
示例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()
示例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
示例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)
示例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)
示例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.")
示例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)
示例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)
示例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)
示例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()
示例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)
示例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
示例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
示例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))
示例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