0

我需要检查一个 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)

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

# HOW I WANT TO MODIFY THE ABOVE CODE TO SET THE TEMPLATES WITH A 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类中并且模块仅包含一个函数时,我可以成功导入库/模块,如下所示:

# THIS IS THE MODULE I AM IMPORTING
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

我将如何修改上述模块代码以使其包含ChkCookie = self.request.cookies.get("cookie")在其中?

4

1 回答 1

0

You can use: http://webapp-improved.appspot.com/api/webapp2.html#webapp2.get_request to get the request instance in your module.

This is the same as passing self.request to your module.

于 2013-11-01T16:33:54.680 回答