python - Integrating a non-threaded SQLAlchemy code with Flask-SQLAlchemy -
i have python module usermanager takes care things user management related - users, groups, rights, authentication. access these assets provided via master class passed sqlalchemy engine parameter @ constructor. engine needed make table-class mappings (using mapper objects), , emit sessions.
this how gobal variables established in app module:
class usermanager: def __init__(self, db): self.db = db self._db_session = none meta = metadata(db) user_table = table( 'usr_user', meta, column('field1'), column('field3') ) mapper(user, user_table) @property def db_session(self): if self._db_session none: self._db_session = scoped_session(sessionmaker()) self._db_session.configure(bind=self.db) return self._db_session class user(object): def init(self, um): self.um = um flask.ext.sqlalchemy import sqlalchemy db = sqlalchemy(app) um = usermanager(db.engine)
this module such designed context-agnostic purpose, can used both locally run , web application.
but here problems arise: time time dreaded "can't reconnect until invalid transaction rolled back" error, presumably caused failed transaction in usermanager code.
i trying identify problem source. maybe not right way how handle database in dynamic context of web server? perhaps have pass db.session um object can sure db connections not mixed up?
in web context should consider request every user isolated. must use flask.g
to share data valid 1 request 1 function another, global variable not enough because break in threaded environments.flask provides special object ensures valid active request , return different values each request. in nutshell: right thing, request , session.
you can see more here.
Comments
Post a Comment