Web interface for a twisted application

回眸只為那壹抹淺笑 提交于 2019-11-30 04:09:35

Since Nevow is still down and I didn't want to write routing and support for a templating lib myself, I ended up using Flask. It turned out to be quite easy:

# make a Flask app
from flask import Flask, render_template, g
app = Flask(__name__)
@app.route("/")
def index():
    return render_template("index.html")

# run in under twisted through wsgi
from twisted.web.wsgi import WSGIResource
from twisted.web.server import Site

resource = WSGIResource(reactor, reactor.getThreadPool(), app)
site = Site(resource)

# bind it etc
# ...

It works flawlessly so far.

You can bind it directly into the reactor like the example below:

reactor.listenTCP(5050, site)
reactor.run()

If you need to add children to a WSGI root visit this link for more details.

Here is an example showing how to combine WSGI Resource with a static child.

from twisted.internet import reactor
from twisted.web import static as Static, server, twcgi, script, vhost
from twisted.web.resource import Resource
from twisted.web.wsgi import WSGIResource
from flask import Flask, g, request

class Root( Resource ):
    """Root resource that combines the two sites/entry points"""
    WSGI = WSGIResource(reactor, reactor.getThreadPool(), app)
    def getChild( self, child, request ):
        # request.isLeaf = True
        request.prepath.pop()
        request.postpath.insert(0,child)
        return self.WSGI
    def render( self, request ):
        """Delegate to the WSGI resource"""
        return self.WSGI.render( request )

def main():
static = Static.File("/path/folder")
static.processors = {'.py': script.PythonScript,
                 '.rpy': script.ResourceScript}
static.indexNames = ['index.rpy', 'index.html', 'index.htm']

root = Root()
root.putChild('static', static)

reactor.listenTCP(5050, server.Site(root))
reactor.run()

Nevow is the obvious choice. Unfortunately the divmod web server hardware and the backup server hardware failed at the same time. They are attempting to recover the data and publish it on launchpad, but it may take a while.

You could also use basically any existing template module with twisted.web; Jinja2 comes to mind.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!