Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide scroped_session context manager #176

Open
rickmak opened this issue Dec 13, 2017 · 0 comments
Open

Provide scroped_session context manager #176

rickmak opened this issue Dec 13, 2017 · 0 comments
Labels

Comments

@rickmak
Copy link
Member

rickmak commented Dec 13, 2017

It is observed that various plugin includes the following function for working with DB directly.

I think we can provide the same function. The good thing of we providing the function gives us a way to config the scoped_session that is the best fit for cloud deployment and different transport.

import logging

from contextlib import contextmanager
from skygear.utils.db import _get_engine
from sqlalchemy.orm import sessionmaker

log = logging.getLogger(__name__)
Session = sessionmaker()


@contextmanager
def scoped_session(session=None):
    if session is None:
        session = _create_session()
    try:
        yield session
        session.commit()
    except:
        log.warn('rollback session')
        session.rollback()
        raise
    finally:
        session.close()


# Usage
with scoped_session() as session:
    session.add(user)
@rickmak rickmak added the vote/1 label Dec 13, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant