~sirn/fanboi2

ref: 834edf0edc5dd633c0ecea16231b6ed2d728476d fanboi2/fanboi2/models/__init__.py -rw-r--r-- 2.2 KiB
834edf0eKridsada Thanabulpong Massive cleanup in preparation for 0.30 (#25) 3 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import logging

from sqlalchemy.engine import engine_from_config
from sqlalchemy.orm import sessionmaker
import zope.sqlalchemy

from ._base import Base
from ._versioned import make_history_event, setup_versioned
from .board import Board
from .page import Page
from .post import Post
from .rule import Rule
from .rule_ban import RuleBan
from .setting import Setting
from .topic import Topic
from .topic_meta import TopicMeta


__all__ = [
    'Base',
    'Board',
    'Page',
    'Post',
    'Rule',
    'RuleBan',
    'Setting',
    'Topic',
    'TopicMeta',
]


_MODELS = {
    'board': Board,
    'page': Page,
    'post': Post,
    'rule': Rule,
    'rule_ban': RuleBan,
    'setting': Setting,
    'topic': Topic,
    'topic_meta': TopicMeta,
}


# Versioned need to be setup after all models are initialized otherwise
# SQLAlchemy won't be able to locate relation tables due to import order.
setup_versioned()


def deserialize_model(type_):
    """Deserialize the given model type string into a model class."""
    return _MODELS.get(type_)


def init_dbsession(dbsession, tm=None):  # pragma: no cover
    """Initialize SQLAlchemy ``dbsession`` with application defaults.

    :param dbsession: A :class:`sqlalchemy.orm.session.Session` object.
    :param tm: A Zope transaction manager.
    """
    zope.sqlalchemy.register(dbsession, transaction_manager=tm)


def configure_sqlalchemy(settings):  # pragma: no cover
    """Configure SQLAlchemy with the given settings."""
    engine = engine_from_config(settings, 'sqlalchemy.')
    Base.metadata.bind = engine
    dbmaker = sessionmaker()
    dbmaker.configure(bind=engine)
    return dbmaker


def includeme(config):  # pragma: no cover
    config.include('pyramid_tm')
    dbmaker = configure_sqlalchemy(config.registry.settings)
    make_history_event(dbmaker)

    log_level = logging.WARN
    if config.registry.settings['server.development']:
        log_level = logging.INFO

    logger = logging.getLogger('sqlalchemy.engine.base.Engine')
    logger.setLevel(log_level)

    def dbsession_factory(context, request):
        dbsession = dbmaker()
        init_dbsession(dbmaker, tm=request.tm)
        return dbsession

    config.register_service_factory(dbsession_factory, name='db')