导入具有类方法(webapp2.RequestHandler)的模块以检查cookie(GAE-Python)

2024-09-30 14:30:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要检查cookie并使用该值来设置加载哪个模板。 以下是工作代码片段:

import webapp2 as webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
import os

class genericPage(webapp.RequestHandler):
    def get(self):
        templatepath = os.path.dirname(__file__) + '/../templates/'
        ChkCookie = self.request.cookies.get("cookie")
        if ChkCookie == 'default':
            html = template.render(templatepath + 'default_header.html', {})
        else:
            html = template.render(templatepath + 'alt_header.html', {})
    self.response.out.write(html)

我的问题是如何将ChkCookie和if…else语句移动到一个单独的模块中,并在上面的代码中调用它。例如:

^{pr2}$

当我将ChkCookie代码保存在genericPage类中并且该模块只包含一个函数时,我可以成功导入库/模块,如下所示:

^{3}$

我该如何修改上面的模块代码使ChkCookie = self.request.cookies.get("cookie")在其中?在


Tags: 模块代码fromimportselfgetcookiehtml