synaptik
synaptik

Reputation: 9509

Pass variable to Python web.py webserver for use by GET/POST handling

I have a simple web.py webserver. Upon a POST request to the webserver, I want to modify an object that I created inside main(). But I can't figure out how to inject a variable into the webserver so that the index class has access to it.

Here is my code:

import web
import multiprocessing

class index:
    def POST(self):
        # modify 'obj' instance of MyObject from main()

class MyWebApp(web.application):
    def run(self, port=8080, *middleware):
        func = self.wsgifunc(*middleware)
        return web.httpserver.runsimple(func, ('0.0.0.0', port))

urls = ( '/', 'index' )
app = MyWebApp(urls, globals())

def launchWebApp(_port=8080):
    app.run(port=_port)

def main():

    obj = MyObject()

    port=36011
    p = multiprocessing.Process(target=launchWebApp, args=(port,))
    p.start()

if __name__ == "__main__":
    main()

How do I make obj accessible to index::POST?

Upvotes: 0

Views: 515

Answers (1)

pbuck
pbuck

Reputation: 4551

You can't really "pass" it, but you can make your obj global, or you can attach it to web.config, which is (also) global. For example.

class index:
    def POST(self):
        web.config.obj.update({'foo': 'bar'})
        ...

def main():
    web.config.obj = MyObject()

...

Upvotes: 3

Related Questions