How to keep a variable value across requests in web.py

安稳与你 提交于 2019-12-08 04:05:22

问题


I want to update logfile as soon as a request comes. I have a class variable event_logging_enabled which is initialised to TRUE. and in the POST() function I check the value of event_logging_enabled.

Now at run time, I modify the value of this flag to FALSE for subsequent requests. But It remains TRUE.

During debugging, I found that when a request is received, a new object get created to handle each request, so, will pick initialized value i.e.TRUE.

This is not the case for other functions like getlogEnabled() of same class. Can you please suggest any work around.

import web
import threading

class webServer(threading.Thread):
    port = "1234"
    event_logging_enabled  = "True"

    def getlogEnabled(self):
        print "Stub getlogEnabled(): ",self.event_logging_enabled

    def __init__(self):
        threading.Thread.__init__(self) 
        """ Logging """
        print "Init------------------------",self.event_logging_enabled
        self.event_logging_filename = "ueLogs.log"

    def run(self):
        urls = (
        '/','webServer',
        )
        app = web.application(urls,globals())
        sys.argv.append(webServer.port)
        app.run()

    def POST(self):
        print "in POST"
        print "Stub POST(): Logging Enabled : ",self.event_logging_enabled

回答1:


I'm not too familiar with web.py framework but in general with web applications, if you need to preserve the state across multiple requests you'll have to manage it with a session object. The session object can be separate for each web user or common for the whole application.

There is a session object in the web.py framework: http://webpy.org/docs/0.3/api#web.session

It lets you decide whether to store the content of the session in a database or directly in a file. The code sample under "DiskStore" on that page shows you how to place a variable in the session.

(By the way in Python boolean literals are True and False, not "True").




回答2:


What I've done in the past and it seems to work alright is if I need to have a variable that's persistent throughout all requests, I jam it onto the web object right before the app.run()

For example, if I want to have a variable called 'foo' that's shared throughout all requests and is persistent between requests, I will do this

web.app = web.application(urls, globals())

# Add my custom foo
web.foo = 'some value'

# Start the app
web.app.run()

Then if I need to modify or use the foo variable, in my code somewhere I'll just

import web

web.foo = 'some other value'

Anything you jam onto the web object in the startup script will be persistent until the app is restarted. A bit of a hack, but it works.



来源:https://stackoverflow.com/questions/7512681/how-to-keep-a-variable-value-across-requests-in-web-py

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!