我试图找到一种方法来记录从 python 代码在 Cassandra 上完成的所有查询。使用 BatchStatement
我可以使用任何钩子(Hook)或回调来记录这个吗?
最佳答案
2个选项:
坚持
session.add_request_init_listener
来自源代码:
a)
绑定(bind)语句
https://github.com/datastax/python-driver/blob/3.11.0/cassandra/query.py#L560
传递的值存储在
raw_values
中,你可以尝试提取它b)
批处理语句
https://github.com/datastax/python-driver/blob/3.11.0/cassandra/query.py#L676
它将用于构造该对象的所有语句和参数存储在
_statements_and_parameters
中。 虽然它不是公共(public)属性(property),但似乎可以获取它c) 只有这个钩子(Hook)被调用了,我没有设法找到任何其他钩子(Hook) https://github.com/datastax/python-driver/blob/master/cassandra/cluster.py#L2097
但它与查询的实际执行无关——它只是一种检查构造了何种查询并可能添加额外回调/错误反馈的方法
从不同的角度接近它并使用痕迹
https://datastax.github.io/python-driver/faq.html#how-do-i-trace-a-request https://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.ResponseFuture.get_all_query_traces
Request tracing can be turned on for any request by setting trace=True in Session.execute_async(). View the results by waiting on the future, then ResponseFuture.get_query_trace()
这是使用选项 2 进行跟踪的 BatchStatement
示例:
bs = BatchStatement()
bs.add_all(['insert into test.test(test_type, test_desc) values (%s, %s)',
'insert into test.test(test_type, test_desc) values (%s, %s)',
'delete from test.test where test_type=%s',
'update test.test set test_desc=%s where test_type=%s'],
[['hello1', 'hello1'],
['hello2', 'hello2'],
['hello2'],
['hello100', 'hello1']])
res = session.execute(bs, trace=True)
trace = res.get_query_trace()
for event in trace.events:
if event.description.startswith('Parsing'):
print event.description
它产生以下输出:
Parsing insert into test.test(test_type, test_desc) values ('hello1', 'hello1')
Parsing insert into test.test(test_type, test_desc) values ('hello2', 'hello2')
Parsing delete from test.test where test_type='hello2'
Parsing update test.test set test_desc='hello100' where test_type='hello1'
关于python - 使用 cassandra-python-driver 记录所有查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46773522/