PostgreSQL侦听/通知功能,通过psycopg2。
psycopg2-pgevents的Python项目详细描述
这个包使得使用postgresql的notify/listen事件系统变得简单 以一种一致的、令人愉快的方式。
注意,这个项目正式支持Python3.6+。这主要是由于 静态输入。
示例
下面显示了正在运行的包的示例。
假设
- PostGreSQL server is running locally.
- default database (^{tt1}$) is available.
- table exists in database in the public schema with the name ^{tt2}$.
frompsycopg2importconnectfrompsycopg2_pgevents.triggerimportinstall_trigger, \ install_trigger_function,uninstall_trigger,uninstall_trigger_functionfrompsycopg2_pgevents.eventimportpoll,register_event_channel, \ unregister_event_channelconnection=connect(dsn='postgres:///postgres')connection.autocommit=Trueinstall_trigger_function(connection)install_trigger(connection,'orders')register_event_channel(connection)try:print('Listening for events...')whileTrue:forevtinpoll(connection):print('New Event: {}'.format(evt))exceptKeyboardInterrupt:print('User exit via Ctrl-C; Shutting down...')unregister_event_channel(connection)uninstall_trigger(connection,'orders')uninstall_trigger_function(connection)print('Shutdown complete.')
故障排除
- 必须启用连接的autocommit属性,此包才能 操作正确。此要求由PostgreSQL的notify/listen提供 机制。
- 与register_event_channel()一起使用的连接必须是 与poll()一起使用,以便接收事件。这是因为 PostgreSQL如何管理“监听”连接。
- 如果要侦听的表不在公共架构中,则 架构名称必须在^{tt6}中作为关键字参数给定$ 方法。