轻松收听PostgreSQL通知
pgnotif的Python项目详细描述
pgnotify:一个python库,可以方便地监听postgresql notify通知
示例
使用简单的for
循环来监听和处理notify事件,如下所示:
frompgnotifyimportawait_pg_notificationsfornotificationinawait_pg_notifications('postgresql:///example',['channel1','channel2']):print(notification.channel)print(notification.payload)
安装
可与来自python包索引的任何python包管理器一起安装,例如:
pip install pgnotify
所有的铃声和口哨声
您还可以处理超时和信号,如在这个更加充实的示例中:
importsignalfrompgnotifyimportawait_pg_notifications,get_dbapi_connection# the first parameter of the await_pg_notifications# loop is a dbapi connection in autocommit modeCONNECT="postgresql:///example"# use this convenient method to create the right connection# from a database URLe=get_dbapi_connection(CONNECT)SIGNALS_TO_HANDLE=[signal.SIGINT,signal.SIGTERM]forninawait_pg_notifications(e,["hello","hello2"],timeout=10,yield_on_timeout=True,handle_signals=SIGNALS_TO_HANDLE,):# the integer code of the signal is yielded on each# occurrence of a handled signalifisinstance(n,int):sig=signal.Signals(n)print(f"handling {sig.name}, stopping")break# the `yield_on_timeout` option makes the# loop yield `None` on timeoutelifnisNone:print("timeout, continuing")# handle the actual notify occurrences hereelse:print((n.pid,n.channel,n.payload))
进一步的文件。