通过导入模块并使用类方法 (webapp2.RequestHandler) 来检查 Cookie (GAE-Python)

47 阅读1分钟

我们需要检查一个 Cookie 并使用其值来设置要加载的模板。以下是可以正常工作的代码片段:

huake_00198_.jpg

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 语句移动到一个单独的模块中,然后在上面的代码中调用它。例如,使用以下方式:

# 希望通过 Cookie 来设置模块的修改方式
import webapp2 as webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
import os
from testmodule import testlibrary

class genericPage(webapp.RequestHandler):
    def get(self):
        html = testlibrary.ChkCookieClass.ChkCookie()
    self.response.out.write(html)

当我们把 ChkCookie 代码留在 genericPage 类中,而模块只包含一个函数时,我们就可以成功导入该库/模块,如下所示:

# 这是要导入的模块
import webapp2 as webapp
from google.appengine.ext.webapp import template
import os

def SkinChk(ChkCookie):
    templatepath = os.path.dirname(__file__) + '/../templates/'
    if ChkCookie == 'default':
        out = template.render(templatepath + 'default_header.html', {})
    else:
        out = template.render(templatepath + 'alt_header.html', {})
    return out

2. 解决方案

要修改模块代码以在其中包含 ChkCookie = self.request.cookies.get("cookie"),我们需要执行以下步骤:

  1. 在模块中创建一个新的类,例如 ChkCookieClass
  2. 在这个类中,定义一个方法,例如 ChkCookie(),并在其中添加 ChkCookie = self.request.cookies.get("cookie")
  3. genericPage 类中,从模块中导入 ChkCookieClass
  4. genericPage 类的 get() 方法中,调用 ChkCookieClass.ChkCookie() 并将结果赋值给 html 变量。

修改后的代码如下:

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

class genericPage(webapp.RequestHandler):
    def get(self):
        html = testlibrary.ChkCookieClass.ChkCookie()
    self.response.out.write(html)

class ChkCookieClass:
    def ChkCookie(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', {})
        return html

通过遵循这些步骤,我们就可以成功地将 ChkCookie 及其 if-else 语句移动到一个单独的模块中,并通过类方法在 genericPage 类中调用它们。