首页 > 解决方案 > 如何将唯一标识符与来自 Python 应用程序的 PostgreSQL 连接相关联?

问题描述

假设我有从多个 Python 实例到同一个 Postgres 数据库的连接。

从 Postgres 服务器,我希望能够识别哪个连接来自哪个实例。我希望能够运行select * from pg_stat_activity where datname = 'db_name'并能够将连接彼此区分开来。

我使用 psycopg2 作为 Python 实例的数据库驱动程序。有没有办法可以将字符串值或 UID 与连接字符串相关联,或者在连接实例化期间以其他方式关联,然后能够在上述查询返回的列之一中看到该值?

标签: pythonpostgresqlpsycopg2

解决方案


您可以使用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')

推荐阅读