python - 如何将唯一标识符与来自 Python 应用程序的 PostgreSQL 连接相关联?
问题描述
假设我有从多个 Python 实例到同一个 Postgres 数据库的连接。
从 Postgres 服务器,我希望能够识别哪个连接来自哪个实例。我希望能够运行select * from pg_stat_activity where datname = 'db_name'
并能够将连接彼此区分开来。
我使用 psycopg2 作为 Python 实例的数据库驱动程序。有没有办法可以将字符串值或 UID 与连接字符串相关联,或者在连接实例化期间以其他方式关联,然后能够在上述查询返回的列之一中看到该值?
解决方案
您可以使用libpq提供的 application_name(可选)参数
import psycopg2 as psp
stuff = {
'dbname': 'twitters',
# 'host': '127.0.0.1',
'user': 'twitwww',
'password': 'secret',
'application_name': 'myap-1.0' }
conn = psp.connect(**stuff) # use kwargs
print(conn)
curs = conn.cursor()
print(curs)
curs.execute("select * from pg_stat_activity where datname = 'twitters' ")
for row in curs:
print ''
print (row)
print ''
conn.close()
结果:
$ python psychopg.py
<connection object at 0x7f40e391a7c0; dsn: 'user=twitwww password=xxxxxxxxxxxx application_name=myap-1.0 dbname=twitters', closed: 0>
<cursor object at 0x7f40e38ff528; closed: 0>
(20529, 'twitters', 2586, 10, 'postgres', 'pgAdmin III - Browser', None, None, None, None, None, None, None, None, None, None, None, None, '<insufficient privilege>', None)
(20529, 'twitters', 25763, 5223264, 'twitwww', 'myap-1.0', None, None, -1, datetime.datetime(2020, 10, 17, 14, 3, 10, 946424, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=120, name=None)), datetime.datetime(2020, 10, 17, 14, 3, 10, 948886, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=120, name=None)), datetime.datetime(2020, 10, 17, 14, 3, 10, 949015, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=120, name=None)), datetime.datetime(2020, 10, 17, 14, 3, 10, 949015, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=120, name=None)), None, None, 'active', None, '119920335', "select * from pg_stat_activity where datname = 'twitters' ", 'client backend')
推荐阅读
- html - 输入“日期”字段不会与 HTML 中的其他字段对齐
- rabbitmq - Spring Actuator RabbitMQ - Prometheus 未显示消息计数
- .net - .Net Core 代码构建问题
- overlay - HERE 地图:在 MapSettingsControl 中动态添加图层
- python - 在 python Tkinter 条目中键入和删除某些内容后保留占位符?
- php - 为什么这个 php 代码给了我一个空白屏幕?
- python - Pandas 使用 df[[]] 选择错误的列
- paypal - 如何在braintree中使用SEPA而不要求贝宝帐户?
- reactjs - 模块/组件执行顺序如何确定?
- python - 如何腌制引用cytpes库的python对象