【问题标题】:refer a string or list global variable in python在 python 中引用字符串或列表全局变量
【发布时间】:2013-11-30 14:45:43
【问题描述】:

python 2.7.2 + tornado 3.1.1中,如何使用全局变量?我需要它在 AppEngine 上工作。

class LoginHandler(BaseHandler):
    def get(self):
        if self.get_current_user():
            self.redirect('/')
            return
        # assign self.get_argument('next', '/')) to the variable next_page
        self.render('login.html')

    def post(self):
        self.set_secure_cookie("user", self.get_argument("username"))
        # direct to next_page

【问题讨论】:

  • “全局变量”到底是什么意思?
  • Tornado 无法在 App Engine 上运行。而且您当然不希望在 App Engine 或 Tornado 上使用全局变量。
  • 是的,在 AppEngine 上运行 tornado 可能是个坏主意。但是tornado 也支持WSGI 和AppEngine。 @丹尼尔罗斯曼

标签: python google-app-engine web global tornado


【解决方案1】:

存储next_page 变量不需要全局变量。尝试使用会话或内存缓存。

from google.appengine.api import memcache

# setup a key/value
memcache.set(key='next_page_%s' % user.id, next_page)

# get next_page
next_page = memcache.get(key='next_page_%s' % user.id)

我们使用'next_page_%s' % user.iduser.id 作为唯一键,否则每个用户将只有一个next_page

【讨论】:

    【解决方案2】:

    您需要在每个函数中将变量分配为全局变量:

    global globalvariable
    

    有关此问题的更多信息,另请参阅 Using global variables in a function other than the one that created them

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多