扭曲应用程序的Web界面

10
我有一个使用Twisted编写的应用程序,想要添加一个Web界面来控制和监视它。我需要许多动态页面来显示当前状态和配置,因此我希望使用至少提供继承和一些基本路由的模板语言的框架。
既然我已经在使用Twisted,我想使用twisted.web - 但它的模板语言太基础了,而且似乎唯一的框架Nevow已经很久没有更新了(它在launchpad上,但主页和wiki都关闭了,我找不到任何文档)。
那么我的选择是什么?
  • 是否有其他基于twisted.web的框架?
  • 是否有其他可以与Twisted的反应堆一起使用的框架?
  • 我应该只获取一个Web框架(我正在考虑web.py或flask)并在线程中运行它吗?
感谢您的回答。

@Jean-Paul Calderone - 我相信Nevow很好;我对所有divmod项目印象深刻。但由于divmod.org崩溃了,对于初学者来说找到文档真的很困难。 - Buttons840
3个回答

14

由于 Nevow 仍无法使用,而我又不想自己编写路由和模板支持功能,所以最终选择了 Flask。结果证明这很容易实现:

# 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
# ...

到目前为止,它运行得非常顺畅。


4
请您详细说明“bind it等”的含义?这样我们就可以得到一个完整的、可运行的示例……对于那些不太熟悉Twisted的人来说,这将非常有帮助 :) - exhuma
1
@exhuma reactor.listenTCP( 80, site ) 将会将 Flask 应用绑定到 80 端口。 - David
现在已经过去两年了。Flask和Twisted仍然活跃,并且我正在考虑做类似的事情。这对你有用吗?还是你遇到了一些问题? - Gerrat
当以这种方式运行时,可以将inlineCallbacks与Flask混合使用吗? - Petrus Theron

6
您可以像下面的示例一样直接将其绑定到反应器中:
reactor.listenTCP(5050, site)
reactor.run()

如果您需要向WSGI根访问添加子项,请参阅此链接以获取更多详细信息。
以下是一个示例,显示如何将WSGI资源与静态子节点结合使用。
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()

3
Nevow是显而易见的选择。不幸的是,divmod网页服务器硬件和备份服务器硬件同时出现故障。他们正在尝试恢复数据并在launchpad上发布,但这可能需要一些时间。 你还可以使用基本上任何现有的模板模块来配合twisted.web; Jinja2是一个很好的选择。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接