Python 如何在挂架应用程序中连接到Cassandra?
我创建了一个新的Pylons项目,并希望使用Cassandra作为我的数据库服务器。我计划使用Pycassa,以便能够使用cassandra 0.7beta。 不幸的是,我不知道在哪里实例化连接以使其在我的应用程序中可用 目标是:Python 如何在挂架应用程序中连接到Cassandra?,python,pylons,cassandra,Python,Pylons,Cassandra,我创建了一个新的Pylons项目,并希望使用Cassandra作为我的数据库服务器。我计划使用Pycassa,以便能够使用cassandra 0.7beta。 不幸的是,我不知道在哪里实例化连接以使其在我的应用程序中可用 目标是: 启动应用程序时创建池 为每个请求从池中获取连接,并使其可用于我的控制器和库(在请求的上下文中)。最好是“懒洋洋地”从游泳池中获得连接,即仅在需要时 如果使用了连接,请在处理请求后释放它 另外,有什么重要的事情我应该知道吗?当我看到一些评论,如“在使用use_thr
- 启动应用程序时创建池
- 为每个请求从池中获取连接,并使其可用于我的控制器和库(在请求的上下文中)。最好是“懒洋洋地”从游泳池中获得连接,即仅在需要时
- 如果使用了连接,请在处理请求后释放它
"""Creating an instance of the Pycassa Pool"""
kwargs = {}
# Parsing servers
if 'cassandra.servers' in config['app_conf']:
servers = config['app_conf']['cassandra.servers'].split(',')
if len(servers):
kwargs['server_list'] = servers
# Parsing timeout
if 'cassandra.timeout' in config['app_conf']:
try:
kwargs['timeout'] = float(config['app_conf']['cassandra.timeout'])
except:
pass
# Finally creating the pool
self.cass_pool = pycassa.QueuePool(keyspace='Keyspace1', **kwargs)
我本可以做得更好,比如在函数中移动它,或者支持更多参数(池大小,…)。我会的
在每次请求时获取连接
嗯。似乎有一种简单的方法:在文件base.py
中,在调用WSGIController
之前添加c.conn=g.cass\u pool.get()
,在调用WSGIController
之后添加c.conn.return\u to\u pool()
之类的内容。这很简单,而且有效。但即使控制器不需要连接,它也会从池中获得连接。我得挖得更深一点
创建连接管理器
我有一个简单的想法,就是创建一个类,该类将在base.py
文件中的每个请求中实例化,并在请求时自动从池中获取连接(并在请求后释放)。这是一个非常简单的类:
class LocalManager:
'''Requests a connection from a Pycassa Pool when needed, and releases it at the end of the object's life'''
def __init__(self, pool):
'''Class constructor'''
assert isinstance(pool, Pool)
self._pool = pool
self._conn = None
def get(self):
'''Grabs a connection from the pool if not already done, and returns it'''
if self._conn is None:
self._conn = self._pool.get()
return self._conn
def __getattr__(self, key):
'''It's cooler to write "c.conn" than "c.get()" in the code, isn't it?'''
if key == 'conn':
return self.get()
else:
return self.__dict__[key]
def __del__(self):
'''Releases the connection, if needed'''
if not self._conn is None:
self._conn.return_to_pool()
在调用WSGIController之前,在base.py
中添加了c.cass=CassandraLocalManager(g.cass_pool)
,之后添加了del(c.cass)
,我就完成了
它的工作原理是:
conn = c.cass.conn
cf = pycassa.ColumnFamily(conn, 'TestCF')
print cf.get('foo')
\o/
我不知道这是不是最好的办法。如果没有,请让我知道=)
另外,我仍然不理解Pycassa源代码中的“同步”部分。如果我的情况需要,我应该如何避免问题
谢谢。好的。我工作多了一点。事实上,使用连接管理器可能不是一个好主意,因为这应该是模板上下文。此外,为每个线程打开连接并不是什么大问题。每个请求打开一个连接将非常困难 我在app\u globals中只使用了
pycassa.connect\u thread\u local()
,我就这样做了