Sesja Gae webapp2: prawidłowy proces tworzenia i sprawdzania sesji
Próbowałem zaimplementować sesję Gae webapp2, ale wydaje się, że jest na ten temat bardzo mało dokumentacji. Zgodnie z http://webapp-improved.appspot.com/api/webapp2_extras/sessions.html , moje kroki są następujące:
1.Konfiguracja i dodanie config do głównej aplikacji:
config = {}
config['webapp2_extras.sessions'] = {
'secret_key': 'my_secret_key',
}
app = webapp2.WSGIApplication([...], config=config)
2.Tworzenie sesji w programie obsługi logowania
# 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.Sprawdź, czy sesja istnieje w różnych miejscach w moim programie
if self.session['account']:
# Session exists
4.Usuń sesję po wylogowaniu się użytkownika
--> not mentioned in the tutorial
Mój pytania:
Dostałem komunikat o błędzie"... obiekt nie posiada atrybutu" session "" podczas procesu tworzenia sesji (Krok 2)
Jak usunąć sesję w krokach 2 i 4?
Czy ogólny proces zarządzania sesją jest prawidłowy?
3 answers
Oto przykład obsługi i jak korzystać z dodatkowych sesji webapp2
Main.py z Basehandlerem i Mainhandlerem
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')
I jeśli masz oddzielny 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')
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-29 19:26:01
Może nie jest to bezpośrednia odpowiedź na to pytanie, ale jest to rozwiązanie, które znalazłem używając gaesessions zamiast sesji Gae webapp2 i chciałbym podzielić się ze wszystkimi. Zaczynamy:
Pobierz gaesessions z https://github.com/dound/gae-sessions klikając przycisk "Pobierz ZIP". Pobrany plik to " Gae-sessions-master.zip".
-
Rozpakuj plik (zostanie utworzony katalog "Gae-sessions-master") i skopiuj katalog " gaessions" do katalogu głównego aplikacji (np. gdzie " app.yaml " is)
-
Utwórz plik o nazwie "appengine_config.py" w katalogu głównym, o następującej treści (skopiowana forma 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
-
Utwórz sesję, gdy użytkownik zaloguje się (zmienna konto jest kontem użytkownika):
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
-
Sprawdź, czy istnieje sesja użytkownika, jeśli tak, zwróć użytkownika konto:
from gaesessions import get_current_session def checkSession(): session = get_current_session() if session.is_active(): return session['account'] return False
-
Usuń sesję po wylogowaniu się użytkownika:
def logout(): session = get_current_session() if session.is_active(): session.terminate()
-
Na koniec możesz utworzyć zadanie cron, aby okresowo czyścić wygasłe sesje:
Cron.yaml:
- description: daily session cleanup
url: /clean_up_sessions
schedule: every day 3:00
timezone: ... (Your time zone)
Funkcja:
from gaesessions import delete_expired_sessions
class clean_up_sessions(webapp2.RequestHandler):
def get(self):
while not delete_expired_sessions():
pass
Mam nadzieję, że to pomoże.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-03 14:11:35
In your RequestHandler
override dispatch
:
from webapp2_extras import sesje
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)
I zrób webapp2.cached_property
o nazwie session
:
@webapp2.cached_property
def session(self):
return self.session_store.get_session(backend="<whatever you want here>")
Gdy chcesz uzyskać dostęp do wartości sesji, robisz self.session[<key>]
self.auth.get_user_by_password(auth_id, password, remember=True,
save_session=True)
Który zajmie się pozbyciem się starej sesji i stworzeniem nowej dla Ciebie, lub:
self.auth.set_session(self.auth.store.user_to_dict(self.user), remember=True)
Jeśli chodzi o wylogowanie, wystarczy zadzwonić:
self.auth.unset_session()
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-26 20:34:09