2016-02-25 82 views
1

我爲會話管理數據庫使用SqlAlchemy,並根據文檔創建了自定義SessionInterface當會話數據庫關閉時,退回Flask的默認會話管理器?

我的開發人員數據庫今天出現故障,現在我無法訪問我的網站,正如預期的那樣。有沒有辦法讓我在這個事件中回到Flask的默認會話管理器?

這是我目前執行的SessionInterface

class SqlAlchemySessionInterface(SessionInterface): 
    #... 
    def open_session(self, app, request): 
     sid = request.cookies.get(app.session_cookie_name) 
     if sid: 
      # error is raised here when database is down 
      stored_session = DBSession.query.filter_by(sid=sid).first() 
      # ... 

我有一個天真的解決崩潰數據庫的問題,即在記憶字典利用了作爲備份:

# A backup memory storage for sessions 
backup = {} 
class SqlAlchemySessionInterface(SessionInterface): 
    #... 
    def open_session(self, app, request): 
     sid = request.cookies.get(app.session_cookie_name) 
     if sid: 
      try: 
       stored_session = DBSession.query.filter_by(sid=sid).first() 
      except DatabaseError: 
       stored_session = backup.get('sid') 
       # ... 

回答

0

你可以擴展默認的secure cookie會話接口實現。

class ReliableSessionInterface(SecureCookieSessionInterface): 
    def open_session(self, app, request): 
     try: 
      return self._open_db_session(app, request) 
     except DatabaseError: 
      return super().open_session(app, request) 

    def save_session(app, session, response): 
     try: 
      self._save_session_to_db(app, session, response) 
     except DatabaseError: 
      super().save_session(app, session, response) 

但是,這樣的要求聽起來有點奇怪。