15

GAE の webapp2 セッションを実装しようとしましたが、それに関するドキュメントはほとんどないようです。http://webapp-improved.appspot.com/api/webapp2_extras/sessions.htmlによると、私の手順は次のとおりです。

1.構成を構成し、メイン アプリケーションに構成を追加します。

config = {}
config['webapp2_extras.sessions'] = {
    'secret_key': 'my_secret_key',
}
app = webapp2.WSGIApplication([...], config=config)

2.ログインハンドラでセッションを作成する

# Delete existent session
  --> not mention in the tutorial
# member is found    
self.session_store = sessions.get_store(request=handler.request)
self.session['account'] = member.account

3.プログラムのさまざまな場所にセッションが存在するかどうかを確認します

if self.session['account']:
    # Session exists

4.ログアウト時にセッションを削除する

--> not mentioned in the tutorial

私の質問:

  1. セッション作成プロセス中に「 ... object has no attribute 'session'」というエラー メッセージが表示されました (ステップ 2)。

  2. 手順 2 と 4 でセッションを削除するにはどうすればよいですか?

  3. 全体的なセッション管理プロセスは正しいですか?

ありがとう。

4

3 に答える 3

16

ハンドラーの例と、webapp2 追加セッションの使用方法を次に示します。

BaseHandler と MainHandler を含む main.py

import webapp2
from webapp2_extras import sessions

class BaseHandler(webapp2.RequestHandler):              # taken from the webapp2 extrta session example
    def dispatch(self):                                 # override dispatch
        # Get a session store for this request.
        self.session_store = sessions.get_store(request=self.request)

        try:
            # Dispatch the request.
            webapp2.RequestHandler.dispatch(self)       # dispatch the main handler
        finally:
            # Save all sessions.
            self.session_store.save_sessions(self.response)

    @webapp2.cached_property
    def session(self):
        # Returns a session using the default cookie key.
        return self.session_store.get_session()

class YourMainHandler(BaseHandler):

    def get(self):

        ....
        self.session['foo'] = 'bar'


    def post(self):


        foo = self.session.get('foo')

そして、別の login.py がある場合:

.... other imports
import main

class Login(main.BaseHandler):

    def get(self):

        ....
        self.session['foo'] = 'bar'


    def post(self):


        foo = self.session.get('foo')
于 2012-12-29T15:17:19.723 に答える
5

これは質問に対する直接の答えではないかもしれませんが、GAEのwebapp2セッションの代わりにgaesessionsを使用して見つけた解決策であり、皆さんと共有したいと思います。どうぞ:

  1. [ZIPのダウンロード]ボタンをクリックして、 https: //github.com/dound/gae-sessionsからgaesessionsをダウンロードします。ダウンロードしたファイルは「gae-sessions-master.zip」です。

  2. ファイルを解凍し(ディレクトリ「gae-sessions-master」が作成されます)、ディレクトリ「gaessions」をアプリケーションのルートディレクトリ(つまり、「app.yaml」)にコピーします。

  3. ルートディレクトリに「appengine_config.py」というファイルを作成します。その内容は次のとおりです(https://github.com/dound/gae-sessions/tree/master/demoからコピー)。

    from gaesessions import SessionMiddleware
    
    # Original comments deleted ... 
    # Create a random string for COOKIE_KDY and the string has to
    # be permanent. "os.urandom(64)" function may be used but do
    # not use it *dynamically*.
    # For me, I just randomly generate a string of length 64
    # and paste it here, such as the following:
    
    COOKIE_KEY = 'ppb52adekdhD25dqpbKu39dDKsd.....'
    
    def webapp_add_wsgi_middleware(app):
        from google.appengine.ext.appstats import recording
        app = SessionMiddleware(app, cookie_key=COOKIE_KEY)
        app = recording.appstats_wsgi_middleware(app)
        return app
    
  4. ユーザーがログインしたときにセッションを作成します(可変アカウントはユーザーのアカウントです)。

    from gaesessions import get_current_session
    session = get_current_session()
    if session.is_active():
        session.terminate()
    # start a session for the user (old one was terminated)
    session['account'] = account
    
  5. ユーザーのセッションが存在するかどうかを確認し、存在する場合は、ユーザーのアカウントを返します。

    from gaesessions import get_current_session
    def checkSession():
        session = get_current_session()
        if session.is_active():
            return session['account']
        return False
    
  6. ユーザーがログアウトしたら、セッションを削除します。

    def logout():
        session = get_current_session()
        if session.is_active():
            session.terminate()
    
  7. 最後に、cronジョブを作成して、期限切れのセッションを定期的にクリーンアップできます。

cron.yaml:

- description: daily session cleanup
  url: /clean_up_sessions
  schedule: every day 3:00
  timezone: ... (Your time zone)

働き:

from gaesessions import delete_expired_sessions
class clean_up_sessions(webapp2.RequestHandler):
    def get(self):
        while not delete_expired_sessions():
            pass

お役に立てれば。

于 2013-01-04T05:54:23.170 に答える
3

あなたのRequestHandlerオーバーライドdispatchで:webapp2_extrasインポートセッションから

def dispatch(self):

    self.session_store = sessions.get_store(request=self.request)

    try:
        webapp2.RequestHandler.dispatch(self)
    finally:
        self.session_store.save_sessions(self.response)

webapp2.cached_property呼ばれるsession

@webapp2.cached_property
def session(self):
    return self.session_store.get_session(backend="<whatever you want here>")

セッション値にアクセスしたいときは、self.session[<key>]

ユーザーがログインすると、次のいずれかを呼び出すことができます。

 self.auth.get_user_by_password(auth_id, password, remember=True,
                                           save_session=True)

これにより、古いセッションが削除され、新しいセッションが作成されます。または:

self.auth.set_session(self.auth.store.user_to_dict(self.user), remember=True)

ログアウトに関する限り、呼び出す必要があるのは次のとおりです。

self.auth.unset_session()
于 2013-08-26T20:34:09.843 に答える