Ejemplo n.º 1
0
    def _test_baked_lazy_loading_relationship_flag(self, flag):
        baked.bake_lazy_loaders()
        try:
            User, Address = self._o2m_fixture(bake_queries=flag)

            sess = Session()
            u1 = sess.query(User).first()

            from sqlalchemy.orm import Query

            canary = mock.Mock()

            # I would think Mock can do this but apparently
            # it cannot (wrap / autospec don't work together)
            real_compile_context = Query._compile_context

            def _my_compile_context(*arg, **kw):
                if arg[0].column_descriptions[0]['entity'] is Address:
                    canary()
                return real_compile_context(*arg, **kw)

            with mock.patch.object(Query, "_compile_context",
                                   _my_compile_context):
                u1.addresses

                sess.expire(u1)
                u1.addresses
        finally:
            baked.unbake_lazy_loaders()

        if flag:
            eq_(canary.call_count, 1)
        else:
            eq_(canary.call_count, 2)
Ejemplo n.º 2
0
    def test_invocation_systemwide_loaders(self):
        baked.bake_lazy_loaders()
        try:
            User, Address = self._o2m_fixture()

            sess = Session()
            q = sess.query(User).options(lazyload(User.addresses))
            with mock.patch.object(BakedLazyLoader, "_emit_lazyload") as el:
                u1 = q.first()
                u1.addresses
                # invoked
                is_(
                    el.mock_calls[0][1][1],
                    u1._sa_instance_state
                )
        finally:
            baked.unbake_lazy_loaders()

        clear_mappers()
        User, Address = self._o2m_fixture()
        sess = Session()
        q = sess.query(User).options(lazyload(User.addresses))

        with mock.patch.object(BakedLazyLoader, "_emit_lazyload") as el:
            u1 = q.first()
            u1.addresses
            # not invoked
            eq_(el.mock_calls, [])
Ejemplo n.º 3
0
    def test_invocation_systemwide_loaders(self):
        baked.bake_lazy_loaders()
        try:
            User, Address = self._o2m_fixture()

            sess = Session()
            q = sess.query(User).options(lazyload(User.addresses))
            with mock.patch.object(BakedLazyLoader, "_emit_lazyload") as el:
                u1 = q.first()
                u1.addresses
                # invoked
                is_(el.mock_calls[0][1][1], u1._sa_instance_state)
        finally:
            baked.unbake_lazy_loaders()

        clear_mappers()
        User, Address = self._o2m_fixture()
        sess = Session()
        q = sess.query(User).options(lazyload(User.addresses))

        with mock.patch.object(BakedLazyLoader, "_emit_lazyload") as el:
            u1 = q.first()
            u1.addresses
            # not invoked
            eq_(el.mock_calls, [])
Ejemplo n.º 4
0
    def test_systemwide_loaders_loadable_via_lazyloader(self):
        from sqlalchemy.orm import configure_mappers

        baked.bake_lazy_loaders()
        try:
            User, Address = self._o2m_fixture(lazy='joined')

            configure_mappers()

            is_(
                User.addresses.property._get_strategy(
                    (('lazy', 'select'), )).__class__, BakedLazyLoader)
        finally:
            baked.unbake_lazy_loaders()
Ejemplo n.º 5
0
    def test_systemwide_loaders_loadable_via_lazyloader(self):
        from sqlalchemy.orm import configure_mappers

        baked.bake_lazy_loaders()
        try:
            User, Address = self._o2m_fixture(lazy='joined')

            configure_mappers()

            is_(
                User.addresses.property.
                _get_strategy((('lazy', 'select'), )).__class__,
                BakedLazyLoader
            )
        finally:
            baked.unbake_lazy_loaders()
Ejemplo n.º 6
0
    def _test_baked_lazy_loading_relationship_flag(self, flag):
        baked.bake_lazy_loaders()
        try:
            User, Address = self._o2m_fixture(bake_queries=flag)

            sess = Session()
            u1 = sess.query(User).first()

            from sqlalchemy.orm import Query

            canary = mock.Mock()

            # I would think Mock can do this but apparently
            # it cannot (wrap / autospec don't work together)
            real_compile_context = Query._compile_context

            def _my_compile_context(*arg, **kw):
                if arg[0].column_descriptions[0]['entity'] is Address:
                    canary()
                return real_compile_context(*arg, **kw)

            with mock.patch.object(
                Query,
                "_compile_context",
                _my_compile_context
            ):
                u1.addresses

                sess.expire(u1)
                u1.addresses
        finally:
            baked.unbake_lazy_loaders()

        if flag:
            eq_(canary.call_count, 1)
        else:
            eq_(canary.call_count, 2)
Ejemplo n.º 7
0
Inheritance Diagram
-------------------

.. inheritance-diagram:: kotti.sqla
"""

from pyramid.compat import json
from pyramid.security import ALL_PERMISSIONS
from pyramid.security import Allow
from sqlalchemy.ext import baked
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.ext.mutable import Mutable
from sqlalchemy.types import TypeDecorator, TEXT

bakery = baked.bakery()
baked.bake_lazy_loaders()


def dump_default(obj):
    if isinstance(obj, MutationDict):
        return obj._d
    elif isinstance(obj, MutationList):
        return obj._d


def no_autoflush(func):
    from kotti.resources import DBSession

    def wrapper(*args, **kwargs):
        with DBSession.no_autoflush:
            return func(*args, **kwargs)
Ejemplo n.º 8
0
Inheritance Diagram
-------------------

.. inheritance-diagram:: kotti.sqla
"""

from pyramid.compat import json
from pyramid.security import ALL_PERMISSIONS
from pyramid.security import Allow
from sqlalchemy.ext import baked
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.ext.mutable import Mutable
from sqlalchemy.types import TypeDecorator, TEXT

bakery = baked.bakery()
baked.bake_lazy_loaders()


def dump_default(obj):
    if isinstance(obj, MutationDict):
        return obj._d
    elif isinstance(obj, MutationList):
        return obj._d


def no_autoflush(func):
    from kotti.resources import DBSession

    def wrapper(*args, **kwargs):
        with DBSession.no_autoflush:
            return func(*args, **kwargs)
Ejemplo n.º 9
0
def main(global_config, **settings):
    """ Return a Pyramid WSGI application. """
    settings = dict(global_config, **settings)
    settings['config_uri'] = global_config['__file__']

    # here we create the engine and bind it to the (not really a) session
    # factory
    settings = set_config(settings)
    if not session_maker_is_initialized():
        configure_engine(settings)
    if settings.get('idealoom_debug_signal', False):
        from assembl.lib import signals
        signals.listen()

    import os
    if 'UWSGI_ORIGINAL_PROC_NAME' in os.environ:
        # uwsgi does not load logging properly
        from pyramid.paster import setup_logging
        setup_logging(global_config['__file__'])

    config = Configurator(registry=getGlobalSiteManager())
    config.include('.lib.logging')
    from .views.traversal import root_factory
    config.setup_registry(settings=settings, root_factory=root_factory)
    config.add_translation_dirs('assembl:locale/')

    config.set_locale_negotiator(my_locale_negotiator)
    config.add_tween('assembl.tweens.logging.logging_tween_factory',
                     over="pyramid_tm.tm_tween_factory")

    config.include('pyramid_retry')
    config.include('.auth')
    config.include('.models')
    bake_lazy_loaders()
    # Tasks first, because it includes ZCA registration (for now)
    config.include('.tasks')

    config.include('pyramid_dogpile_cache')
    config.include('.lib.zmqlib')
    session_factory = session_factory_from_settings(settings)
    config.set_session_factory(session_factory)
    if not settings.get('nosecurity', False):
        # import after session to delay loading of BaseOps
        from .auth.util import authentication_callback
        auth_policy_name = settings.get(
            "auth_policy_class",
            "assembl.auth.util.UpgradingSessionAuthenticationPolicy")
        auth_policy = resolver.resolve(auth_policy_name)(
            callback=authentication_callback)
        config.set_authentication_policy(auth_policy)
        config.set_authorization_policy(ACLAuthorizationPolicy())
    # ensure default roles and permissions at startup
    if not settings.get('in_migration', False):
        from .lib.migration import bootstrap_db, bootstrap_db_data
        db = bootstrap_db(settings['config_uri'])
        bootstrap_db_data(db, settings['config_uri'] != "testing.ini")

    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_static_view('widget', 'widget', cache_max_age=3600)
    config.include('cornice')  # REST services library.
    # config.include('.lib.alembic')
    # config.include('.lib.email')
    config.include('.lib')
    config.include('.views')

    # jinja2
    config.include('pyramid_jinja2')
    config.add_jinja2_extension('jinja2.ext.i18n')

    # Mailer
    if 'pyramid_mailer.debug' not in settings.get('pyramid.includes', ()):
        config.include('pyramid_mailer')

    config.include('.view_def')

    wsgi_app = config.make_wsgi_app()
    if asbool(settings.get('sqltap', False)):
        import sqltap.wsgi
        wsgi_app = sqltap.wsgi.SQLTapMiddleware(wsgi_app)
    return wsgi_app
Ejemplo n.º 10
0
def main(global_config, **settings):
    """ Return a Pyramid WSGI application. """
    settings['config_uri'] = global_config['__file__']

    # here we create the engine and bind it to the (not really a) session
    # factory
    set_config(settings)
    if not session_maker_is_initialized():
        configure_engine(settings)
    if settings.get('assembl_debug_signal', False):
        from assembl.lib import signals
        signals.listen()

    from views.traversal import root_factory
    config = Configurator(registry=getGlobalSiteManager())
    config.setup_registry(settings=settings, root_factory=root_factory)
    config.add_translation_dirs('assembl:locale/')

    global locale_negotiator
    locale_negotiator = my_locale_negotiator
    config.set_locale_negotiator(my_locale_negotiator)
    if using_virtuoso():
        config.add_tween(
            'assembl.tweens.virtuoso_deadlock.transient_deadlock_tween_factory',
            under="pyramid_tm.tm_tween_factory")

    config.include('.auth')
    config.include('.models')
    bake_lazy_loaders()
    # Tasks first, because it includes ZCA registration (for now)
    config.include('.tasks')

    config.include('pyramid_dogpile_cache')
    config.include('.lib.zmqlib')
    session_factory = session_factory_from_settings(settings)
    config.set_session_factory(session_factory)
    if not settings.get('nosecurity', False):
        # import after session to delay loading of BaseOps
        from auth.util import authentication_callback
        auth_policy_name = settings.get(
            "auth_policy_class", "assembl.auth.util.UpgradingSessionAuthenticationPolicy")
        auth_policy = resolver.resolve(auth_policy_name)(
            callback=authentication_callback)
        config.set_authentication_policy(auth_policy)
        config.set_authorization_policy(ACLAuthorizationPolicy())
    # ensure default roles and permissions at startup
    from models import get_session_maker
    with transaction.manager:
        session = get_session_maker()
        from .lib.migration import bootstrap_db_data
        bootstrap_db_data(session, False)

    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_static_view('widget', 'widget', cache_max_age=3600)
    config.include('cornice')  # REST services library.
    # config.include('.lib.alembic')
    # config.include('.lib.email')
    config.include('.lib')
    config.include('.views')

    # jinja2
    config.include('pyramid_jinja2')
    config.add_jinja2_extension('jinja2.ext.i18n')

    # Mailer
    config.include('pyramid_mailer')

    config.include('.view_def')

    wsgi_app = config.make_wsgi_app()
    if asbool(settings.get('sqltap', False)):
        wsgi_app = sqltap.wsgi.SQLTapMiddleware(wsgi_app)
    return wsgi_app