如何在 sqlalchemy+psycopg2 中处理不断变化的密码? [英] how to handle ever-changing password in sqlalchemy+psycopg2?

查看:28
本文介绍了如何在 sqlalchemy+psycopg2 中处理不断变化的密码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我继承了一些使用 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():

creator – 返回 DBAPI 连接的可调用对象.此创建函数将传递给底层连接池,并将用于创建所有新的数据库连接.使用此函数会导致绕过 URL 参数中指定的连接参数.

creator – a callable which returns a DBAPI connection. This creation function will be passed to the underlying connection pool and will be used to create all new database connections. Usage of this function causes connection parameters specified in the URL argument to be bypassed.

只需修改您的 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 中处理不断变化的密码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆