summaryrefslogtreecommitdiffstats
path: root/kittystore/storm/__init__.py
blob: 2ea90eee9f8e094d5b9e865599a30fce16e17bc9 (plain)
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
# -*- coding: utf-8 -*-

from __future__ import absolute_import, with_statement

import sys
import threading

import storm.tracer
from storm.locals import create_database, Store
from storm.schema.schema import Schema

from .model import List, Email
from . import schema
from .store import StormStore
from .search import SearchEngine


class ThreadSafeStorePool(object):
    """
    Storm does not have a thread pool, like SQLAlchemy. Solve the threading
    problem by keeping the store in a thread-local object.

    http://unpythonic.blogspot.fr/2007/11/using-storm-and-sqlite-in-multithreaded.html
    """

    def __init__(self, url, debug):
        self.url = url
        self.debug = debug
        self._local = threading.local()

    def get(self):
        try:
            return self._local.store
        except AttributeError:
            self._local.store = create_store(self.url, self.debug)
            return self._local.store


def create_store(settings, debug):
    if debug:
        storm.tracer.debug(True, stream=sys.stdout)
    url = settings.KITTYSTORE_URL
    database = create_database(url)
    dbtype = url.partition(":")[0]
    store = Store(database)
    dbschema = Schema(schema.CREATES[dbtype], [], [], schema)
    dbschema.upgrade(store)
    search = settings.KITTYSTORE_SEARCH_INDEX
    if search is not None:
        search_index = SearchEngine(search)
    else:
        search_index = None
    return StormStore(store, search_index, settings, debug)


def get_storm_store(settings, debug=False):
    # Thread safety is managed by the middleware
    #store_pool = ThreadSafeStorePool(url, debug)
    #return store_pool.get()
    return create_store(settings, debug)