Invoking a pyramid framework application from inside another application

I have a Python application running in a framework that drives a network protocol to control remote devices. Now I want to add a browser-based monitoring and control and I am looking at the Pyramid framework to build it.

Normally you start a Pyramid application using pserve from a command line, but I can't find any documentation or examples for how to invoke it inside a host application framework. This needs to be done in such a way that the Pyramid code can access objects in the host application.

Is this a practical use case for Pyramid or should I be looking for some other WSGI-based framework to do this?


A WSGI app is basically a function which receives some input and returns a response, you don't really need pserve to serve a WSGI app, it's more like a wrapper which assembles an application from an .ini file.

Have a look at Creating Your First Pyramid Application chapter in Pyramid docs:

from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response

def hello_world(request):
    return Response('Hello %(name)s!' % request.matchdict)

if __name__ == '__main__':
    config = Configurator()
    config.add_route('hello', '/hello/{name}')
    config.add_view(hello_world, route_name='hello')
    app = config.make_wsgi_app()
    server = make_server('0.0.0.0', 8080, app)
    server.serve_forever()

the last two lines create a server which listens on port 8080.

Now, the trickier problem is that the serve_forever call is blocking, iethe program stops on that line until you hit Ctrl-C and stop the script. This makes it a bit non-trivial to have your program to "drive a network protocol to control remote devices" and to serve web pages at the same time (this is unlike other event-based platforms such as Node.js where it's trivial to have two servers to listen on different ports within the same process).

One possible solution to this problem would be to run the webserver in a separate thread.

链接地址: http://www.djcxy.com/p/69098.html

上一篇: 苹果电脑上的Flash和AIR技术

下一篇: 从另一个应用程序中调用金字塔框架应用程序