如何为数据库中的所有表生成RethinkDB更改源

时间:2017-01-09 12:17:00

标签: python rethinkdb reql

我正在测试一个在RethinkDB数据库的多个表中插入或删除数据的API。为了监控使用API​​时数据库发生的情况,我想在所有表格中打印更改。

以下是一些'伪代码'我试图实现的目标:

import rethinkdb as r

# Prior to running this script, run "rethinkdb --port-offset 1" at the command line
conn = r.connect('localhost', 28016)
if 'test' in r.db_list().run(conn):
    r.db_drop('test').run(conn)
r.db_create('test').run(conn)

r.table_create('table1').run(conn)
r.table_create('table2').run(conn)

feed = r.table('table1' and 'table2').changes().run(conn)
for document in feed:
    print document

在运行此脚本之前,我将运行rethinkdb --port-offset 1来初始化RethinkDB数据库。

此脚本运行后,我想将数据插入table1table2(例如,使用localhost:8081处的网络用户界面)并查看在运行脚本的终端中打印的更改。但是,这似乎不起作用  因为r.table('table1' and 'table2')可能不是有效的ReQL查询。

如何监控两个表中的更改?

2 个答案:

答案 0 :(得分:5)

您可以使用r.union在单个查询中关注多个更改Feed:

r.union(
  r.table('table1').changes(),
  r.table('table2').changes()
).run(conn)

答案 1 :(得分:1)

我最终在一个单独的线程中运行每个表的更改源:

import rethinkdb as r
import threading

# Prior to running this script, run "rethinkdb --port-offset 1" at the command line
conn = r.connect('localhost', 28016)

def clear_test_database():
    '''Clear the contents of the "test" database by dropping and re-creating it.'''
    if 'test' in r.db_list().run(conn):
        r.db_drop('test').run(conn)
    r.db_create('test').run(conn)

clear_test_database()

def monitor_changes(table_name, conn):
    feed = r.table(table_name).changes().run(conn)
    for document in feed:
        print document

tables = ['table1', 'table2']

for table in tables:
    conn = r.connect('localhost', 28016)
    r.table_create(table).run(conn)
    thread = threading.Thread(target=monitor_changes, args=(table, conn))
    thread.start()

请注意,我在for循环中重新定义了conn连接对象,因为这些对象不是线程安全的。

为了测试该方法,我在localhost:8081打开了Web UI并使用了以下insert命令:

enter image description here

在Sublime跑步者中,我看到每次按下" Run"时都会添加更改。按钮:

enter image description here

当我在table1命令中选择table2insert时,此功能都适用。

相关问题