使用twistd提供金字塔应用程序

时间:2012-10-29 13:24:51

标签: python twisted pyramid

我有一个Pyramid应用程序,里面还有一些Twisted代码,因此我想使用twistd来一起杀死两只鸟。

这是我的.tac文件:

from twisted.web.server import Site
from twisted.web.wsgi import WSGIResource
from twisted.internet import reactor
from twisted.application import internet, service
import os

from pyramid.paster import get_app, setup_logging

config='/path/to/app/production.ini'
config = os.path.abspath(config)
port = 8888

application = get_app(config, 'main')

# Twisted WSGI server setup...
resource = WSGIResource(reactor, reactor.getThreadPool(), application)
factory = Site(resource)

service = internet.TCPServer(port, factory)

service.setServiceParent(application)

为了运行这个,我使用了:

twistd -y myApp.tac

我收到错误告诉我get_app()方法没有返回可以这种方式使用的对象。 E.g:

"Failed to load application: 'PrefixMiddleware' object has no attribute 'addService'"

使用twistd运行Pyramid应用程序的最佳方法是什么?

2 个答案:

答案 0 :(得分:3)

您可以在Twisted Web的twistd插件中使用WSGI支持来缩短它并使其更易于配置。创建一个这样的模块:

from pyramid.paster import get_app

config = '/path/to/app/production.ini'
myApp = get_app(config, 'main')

然后像这样运行twistd

$ twistd web --port tcp:8888 --wsgi foo.myApp

其中foo是您创建的模块的名称。

答案 1 :(得分:2)

我找到了一个有效的解决方案。这是工作的.tac文件:

from twisted.web.server import Site
from twisted.web.wsgi import WSGIResource
from twisted.internet import reactor
from twisted.application import internet, service
import os

from pyramid.paster import get_app, setup_logging

config='/path/to/app/production.ini'
config = os.path.abspath(config)
port = 8888

# Get the WSGI application
myApp = get_app(config, 'main')

# Twisted WSGI server setup
resource = WSGIResource(reactor, reactor.getThreadPool(), myApp)
factory = Site(resource)

# Twisted Application setup
application = service.Application('mywebapp')
internet.TCPServer(port, factory).setServiceParent(application)

get_app()获取Pyramid WSGI应用程序,而internet.TCPServer需要Twisted Application对象,因此不应混淆。

此代码将在TCP端口8888上启动应用程序。

如果有人有更好/更清楚的方法来实现这一点,请添加你的答案。

相关问题