问题描述
我继承了一些将sqlalchemy与psycopg2一起使用的代码,该代码需要在AWS上运行. RDS Postgres支持基于Iam的身份验证,但这样做的方式相当笨拙:您使用AWS RDS API请求一个临时密码,该密码的有效时间约为15分钟,然后将其作为密码传递.
I inherited some code that uses sqlalchemy with psycopg2, which needs to run on AWS. RDS Postgres supports iam-based authentication, but the way it does it is rather kludgy: you request a temporary password using the AWS RDS API, which is good for about 15 minutes, and you pass that as the password.
我有效地执行了e = create_engine(make_sqlalchemy_string())
的代码,其中make_sqlalchemy_string()
进行了aws api调用,获得了临时密码,并且一段时间以来一切都很好.除了什么以外,sqlalchemy代码中的某处关闭了连接,然后密码不再有效.是否已经有一种方法可以使sqlalchemy每次需要重新连接时都请求一个新的连接字符串?
The code I have effectively does e = create_engine(make_sqlalchemy_string())
, where make_sqlalchemy_string()
makes an aws api call, gets the temporary password, and everything is good for a while. Except something, somewhere in the sqlalchemy code closes the connection, and then the password is no longer good. Is there already a way to make sqlalchemy request a new connection string every time it needs to reconnect?
我可以想到许多解决方法,但是都不是令人满意的方法.是否有实现这一目标的标准方法?
I can think of a number of workarounds, but none of them are pleasant. Is there a standard way of achieving this?
谢谢
推荐答案
一种方法是使用 create_engine()
:
One approach would be to use the creator
argument of create_engine()
:
只需修改您的make_sqlalchemy_string()
即可为 psycopg2.connect()
,这可能意味着完全不必修改,因为已接受连接字符串格式,并传递创建者:
Just modify your make_sqlalchemy_string()
to produce the dsn
argument for psycopg2.connect()
, which might mean not having to modify it at all due to accepted connection string formats, and pass the creator:
create_engine('postgresql://', creator=lambda: psycopg2.connect(make_dsn_string()))
这篇关于如何处理sqlalchemy + psycopg2中不断变化的密码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!