如何为数据库中的所有表生成rejectdb changefeed

2024-05-18 07:34:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在测试一个API,它在reinstdb数据库的多个表中插入或删除数据。为了在使用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来初始化rewingdb数据库。在

一旦这个脚本运行,我想将数据插入table1table2(例如,使用localhost:8081的web UI),并查看运行脚本的终端中打印的更改。然而,这似乎行不通, 因为r.table('table1' and 'table2')可能不是有效的ReQL查询。在

如何监视两个表中的更改?在


Tags: 数据runtest脚本api数据库dbport
2条回答

您可以使用r.union在一个查询中跟踪多个changefeeds:

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

最后,我在一个单独的线程中为每个表运行changefeeds:

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 runner中,每次按下“Run”按钮,我都会看到添加的更改:

enter image description here

当我在insert命令中选择table1table2时,这两种方法都有效。在

相关问题 更多 >