-
Notifications
You must be signed in to change notification settings - Fork 6
/
flask_cassandra.py
69 lines (55 loc) · 2.11 KB
/
flask_cassandra.py
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
# -*- coding: utf-8 -*-
'''
flask-cassandra
---------------
Flask-Cassandra provides an application-level connection
to an Apache Cassandra database. This connection can be
used to interact with a Cassandra cluster.
:copyright: (c) 2015 by Terbium Labs.
:license: BSD, see LICENSE for more details.
'''
__version_info__ = ('0', '1', '3')
__version__ = '.'.join(__version_info__)
__author__ = 'Michael Moore'
__license__ = 'BSD'
__copyright__ = '(c) 2015 by TerbiumLabs'
from cassandra.cluster import Cluster
import logging
from flask import current_app
log = logging.getLogger(__name__)
try:
from flask import _app_ctx_stack as stack
except ImportError:
from flask import _request_ctx_stack as stack
class CassandraCluster(object):
def __init__(self, app=None):
self.app = app
if app is not None:
self.init_app(app)
def init_app(self, app):
app.config.setdefault('CASSANDRA_CLUSTER', ':memory:')
if hasattr(app, 'teardown_appcontext'):
app.teardown_appcontext(self.teardown)
else:
app.teardown_request(self.teardown)
def connect(self):
log.debug("Connecting to CASSANDRA NODES {}".format(current_app.config['CASSANDRA_NODES']))
if isinstance(current_app.config['CASSANDRA_NODES'], (list, tuple)):
cluster = Cluster(current_app.config['CASSANDRA_NODES'])
elif isinstance(current_app.config['CASSANDRA_NODES'], (str, unicode)):
cluster = Cluster([current_app.config['CASSANDRA_NODES']])
else:
raise TypeError("CASSANDRA_NODES must be defined as a list, tuple, string, or unicode object.")
online_cluster = cluster.connect()
return online_cluster
def teardown(self, exception):
ctx = stack.top
if hasattr(ctx, 'cassandra_cluster'):
ctx.cassandra_cluster.shutdown()
@property
def connection(self):
ctx = stack.top
if ctx is not None:
if not hasattr(ctx, 'cassandra_cluster'):
ctx.cassandra_cluster = self.connect()
return ctx.cassandra_cluster