how to get cookies values on google app engine tem

2020-02-26 02:05发布

I'm developing an application to learn about python and Google App Engine. I would like to get values from cookies and print on templates to hide or show some content.

Is it possible?

What kind of session system is the best to use with google app engine?

What could it be the best way to use sessions on gae and templates?

How can i validate the value of the cookies using templates?

1条回答
放荡不羁爱自由
2楼-- · 2020-02-26 02:43

remember that Google App Engine is a platform, not a framework, so your question would be if webapp2 (the default framework used in GAE) has a nice interface to deal with cookies. Even if the framework doesn't have this interface, as long as you have access to the Cookie header of the request you can have access to cookies.

Here are two examples, one using the webapp2 cookies interface, and the other just using the Cookie header.

webapp2:

class MyHandler(webapp2.RequestHandler):
    def get(self):
        show_alert = self.request.cookies.get("show_alert")
        ...

Cookie header (using webapp2):

# cookies version 1 is not covered
def get_cookies(request):
    cookies = {}
    raw_cookies = request.headers.get("Cookie")
    if raw_cookies:
        for cookie in raw_cookies.split(";"):
            name, value = cookie.split("=")
            for name, value in cookie.split("="):
                cookies[name] = value
    return cookies


class MyHandler(webapp2.RequestHandler):
    def get(self):
        cookies = get_cookies(self.request)
        show_alert = cookies.get("show_alert")
        ...

The same is for sessions, although making your own session library is more difficult, anyway, webapp2 have you covered:

from webapp2_extras import sessions

class MyBaseHandler(webapp2.RequestHandler):
    def dispatch(self):
        # get a session store for this request
        self.session_store = sessions.get_store(request=self.request)
        try:
            # dispatch the request
            webapp2.RequestHandler.dispatch(self)
        finally:
            # save all sessions
            self.session_store.save_sessions(self.response)

    @webapp2.cached_property
    def session(self):
        # returns a session using the backend more suitable for your app
        backend = "securecookie" # default
        backend = "datastore" # use app engine's datastore
        backend = "memcache" # use app engine's memcache
        return self.session_store.get_session(backend=backend)

class MyHandler(MyBaseHandler):
    def get(self):
        self.session["foo"] = "bar"
        foo = self.session.get("foo")
        ...

see webapp documentation for more information about sessions and cookies.

About your question regarding the templates, again, you should look at the documentation of the template engine your using and look for what you need to know.

查看更多
登录 后发表回答