如何与Python的Posgres连接?

发布于 2025-01-26 11:22:33 字数 1817 浏览 4 评论 0原文

我遵循 documentation 我添加了:

import os
import psycopg2

DATABASE_URL = os.environ['postgres://sficoXXX:[email protected]:5432/database-name']

conn = psycopg2.connect(DATABASE_URL, sslmode='require')

我从会话config vars获取的URL(我使用了:heroku pg:recertentials:url)。

当我使用HEROKU PG检查到数据库的连接时,PSQL似乎一切正常。

但是部署后显示以下错误:

无法创建会话: 'postgres://sficoXXX:[email protected]:5432/database-姓名' Trackback(最近的最新通话):文件 “ /users/spoleto/.pyenv/versions/3.8.13/lib/python3.8/site-packages/otree/session.py”, 第447行,在create_session_traceback_wrapper中 返回create_session(** kwargs)文件“/users/spoleto/.pyenv/versions/3.8.13/lib/python3.8/site-packages/otree/session.py”, 第418行,在create_session中 func(sissession)文件“/users/spoleto/pycharmprojects/upstream-reciprocity/prototypes/consent/consent/prototypes/consent/protongnong> init> init .py”, 第35行,在创建中 database_url = os.environ [postgres:// sficoxxx: [email  prectioned] :5432/数据库名称'] file“/users/spoleto/.pyenv/versions/3.8.13/lib/python3.8/os.py”,line 675,在 getItem 中 从无无

我是这样吗?错误从何而来?应该如何建立连接?

这几乎是文档中的副本/粘贴。

I have followed the documentation and in my Python code I've added:

import os
import psycopg2

DATABASE_URL = os.environ['postgres://sficoXXX:[email protected]:5432/database-name']

conn = psycopg2.connect(DATABASE_URL, sslmode='require')

The URL I took from the session Config Vars (I used: heroku pg:credentials:url).

When I check the connection to the database using heroku pg:psql everything seems to be working fine.

But after deploying it shows the following error:

Failed to create session:
'postgres://sficoXXX:[email protected]:5432/database-name'
Traceback (most recent call last): File
"/Users/spoleto/.pyenv/versions/3.8.13/lib/python3.8/site-packages/otree/session.py",
line 447, in create_session_traceback_wrapper
return create_session(**kwargs) File "/Users/spoleto/.pyenv/versions/3.8.13/lib/python3.8/site-packages/otree/session.py",
line 418, in create_session
func(subsession) File "/Users/spoleto/PycharmProjects/upstream-reciprocity/prototypes/Consent/init.py",
line 35, in creating_session
DATABASE_URL = os.environ[postgres://sficoXXX:[email protected]:5432/database-name']
File "/Users/spoleto/.pyenv/versions/3.8.13/lib/python3.8/os.py", line
675, in getitem
raise KeyError(key) from None

Am I doing this right? Where does the error come from? How is the connection supposed to be established?

This is almost a copy/paste from the documentation.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吹梦到西洲 2025-02-02 11:22:33

将连接字符串放入环境变量的全部要点是,它不需要在源代码中。

的值

DATABASE_URL = os.environ['DATABASE_URL']

与其查找database_url 每次运行时都会动态地查找具有该名称的环境变量,并将您的database_url变量设置为database_url环境变量的值。

(您在问题中显示的代码寻找一个名为postgres的环境变量:// ...,它不太可能存在。)

请注意,这将失败,而indexerror代码>如果无法找到名为database_url的环境变量。这样做的一种更安全的方法可能是使用.get()方法(请确保使用圆形括号而不是方括号):

DATABASE_URL = os.environ.get('DATABASE_URL')

现在您甚至可以提供后备,例如本地开发:

DATABASE_URL = os.environ.get('DATABASE_URL') or "postgres://postgres:postgres@localhost:5432/postgres"

注意:您没有在问题中泄漏整个连接字符串,但我建议您旋转您的凭据无论如何:

heroku pg:credentials:rotate

这将无效旧连接字符串并生成新的连接字符串。

好消息是您的database_url环境变量将自动更新,并且由于您的代码现在在运行时读取该值,因此它将继续工作!

The whole point of putting a connection string into an environment variable is so it doesn't need to be in your source code.

Instead of looking up the value of DATABASE_URL manually and pasting it into your source code, use the name of the environment variable:

DATABASE_URL = os.environ['DATABASE_URL']

Now your code will look for an environment variable with that name dynamically every time it runs, and set your DATABASE_URL variable to the value of the DATABASE_URL environment variable.

(The code you show in your question looks for an environment variable named postgres://..., which is very unlikely to exist.)

Note that this will fail with an IndexError if an environment variable named DATABASE_URL cannot be found. A safer way of doing this might be to use the .get() method (make sure to use round parentheses instead of square brackets):

DATABASE_URL = os.environ.get('DATABASE_URL')

Now you can even provide a fallback, e.g. for local development:

DATABASE_URL = os.environ.get('DATABASE_URL') or "postgres://postgres:postgres@localhost:5432/postgres"

Note: You didn't leak your whole connection string in your question, but I suggest you rotate your credentials anyway:

heroku pg:credentials:rotate

This will invalidate the old connection string and generate a new one.

The good news is that your DATABASE_URL environment variable will automatically be updated, and since your code now reads that value at runtime, it will continue to work!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文