扭曲应用的网页界面
我有一个用Twisted写的应用程序,我想给它加一个网页界面,用来控制和监控这个应用。因为我需要很多动态页面来显示当前的状态和配置,所以我希望能找到一个框架,至少要有一个支持继承的模板语言和一些基本的路由功能。
由于我已经在使用Twisted,我想用twisted.web
,但是它的模板语言太简单了,而且看起来唯一的框架Nevow已经不活跃了(它在launchpad上,但主页和维基都无法访问,我找不到任何文档)。
那么我还有哪些选择呢?
- 有没有其他基于
twisted.web
的框架? - 有没有其他框架可以和Twisted的反应器一起工作?
- 我是不是应该直接用一个网页框架(我在考虑web.py或者flask),然后在一个线程里运行它?
谢谢大家的回答。
3 个回答
3
Nevow 是一个很不错的选择。不过不幸的是,divmod 的网络服务器和备用服务器的硬件同时坏掉了。他们正在努力恢复数据,并计划在 launchpad 上发布这些数据,但可能需要一些时间。
你也可以用任何现有的模板模块来搭配 twisted.web,像 Jinja2 就是一个不错的选择。
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()
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
# ...
到目前为止,它运行得非常顺利。