Issue 852 upgrade sqlalchemy

This PR improves the code to support latest version of SQLAlchemy as well as Flask-SQLAlchemy. Up to now, we were running in a very old-fashioned version of SQLAlchemy.