如何在 web.py 中跨请求保持变量值 [英] How to keep a variable value across requests in web.py

查看:19
本文介绍了如何在 web.py 中跨请求保持变量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在收到请求后立即更新日志文件.我有一个初始化为 TRUE 的类变量 event_logging_enabled.在 POST() 函数中,我检查了 event_logging_enabled 的值.

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.

现在在运行时,我将此标志的值修改为 FALSE 以用于后续请求.但它仍然是正确的.

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

在调试过程中,我发现当收到请求时,会创建一个新对象来处理每个请求,因此,会选择初始化值,即 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.

对于同一个类的其他函数,如 getlogEnabled(),情况并非如此.你能提出任何解决方法吗.

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

推荐答案

我对 web.py 框架不太熟悉,但总的来说,对于 Web 应用程序,如果您需要跨多个请求保留状态,则必须使用会话对象管理它.会话对象可以是每个网络用户的单独对象,也可以是整个应用程序的公共对象.

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.

web.py框架中有一个会话对象:http://webpy.org/docs/0.3/api#web.session

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

它让您决定是将会话的内容存储在数据库中还是直接存储在文件中.该页面上DiskStore"下的代码示例向您展示了如何在会话中放置变量.

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.

(顺便说一句,在 Python 中布尔文字是 True 和 False,而不是True").

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

这篇关于如何在 web.py 中跨请求保持变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆