开发者

Global objects in python wsgi server

I am creating an application in python which uses a web server to serve the frontend, and after accepting data as a web request, forwards the task to a job queue, which is being shared with the main processing function using a thread.

But the problem is that python web server tries to import its开发者_运维技巧elf to run threads, and in this process for nearly each request a new Job Queue is created, which breaks the logic. Is there any way by which a global variable can be setup in python web servers, since python Queue are thread-safe, I am assuming that it won't do any harm.

(I tried two web servers Flask and web.py)


Shared data is best stored in a database.

If you want a global variable per user's session, then you want to store these with the session data: here are details for web.py and for flask.

If you have a persistent process that is processing a queue, you might look at running your server with FastCGI, where your python server can run in a separate instance from your web server. Check out how to configure FastCGI for web.py - see if perhaps that is appropriate. The web server would communicate to the python server through it's own port, so your python server could keep running and maintain any global data.

[edit]

Since you need to share variables - you might check out flask.g for flask, or web.ctx for web.py. I've never used them - so I don't know if there are evil implications or performance issues. I saw an example here which suggested in web.py to do something like:

import web

def add_global_hook():
    g = web.storage({"counter": 0})
    def _wrapper(handler):
        web.ctx.globals = g
        return handler()
    return _wrapper

class Hello:
    def GET(self):
        web.ctx.globals.counter += 1
        return "<h1>Counter: %d</h1>" % web.ctx.globals.counter

if __name__ == '__main__':
    urls = ("/", "Hello")
    app = web.application(urls, globals())
    app.add_processor(add_global_hook())
    app.run()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜