Python 我应该如何设置我的 DATABASE_URL?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30044904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How should I set my DATABASE_URL?
提问by James Kelleher
I'm working on my first-ever Heroku/Django app. I just want to be sure I'm setting my DATABASE_URL
and DATABASES
variables correctly. Here's what's in my code:
我正在开发我的第一个 Heroku/Django 应用程序。我只是想确保我正确设置了变量DATABASE_URL
和DATABASES
变量。这是我的代码中的内容:
import dj_database_url
DATABASE_URL = 'postgresql:///my_app'
# Parse database configuration from $DATABASE_URL
DATABASES = {
'default': dj_database_url.config(default=DATABASE_URL)
}
When I just have DATABASES['default'] = dj_database_url.config()
and I try to use Django commands like run server
or migrate
I get the following error: NameError: name 'DATABASES' is not defined
. I set the DATABASE_URL
since doing so appears to solve this issue (after I create the my_app
database).
当我刚刚DATABASES['default'] = dj_database_url.config()
尝试使用 Django 命令时,run server
或者migrate
我收到以下错误:NameError: name 'DATABASES' is not defined
. 我设置了DATABASE_URL
因为这样做似乎解决了这个问题(在我创建my_app
数据库之后)。
Everything appears to be working fine as I code and test, but I've also seen a half-dozen different ways to set the database variables on the internet. If this isn't correct, I'd like to fix it now. The thing that really confuses me is, when I push my app to Heroku, how will the data get pushed to the web, when the database is /usr/local/var/postgres? Or will this not happen at all? Am I just too confused/tired at this point?
在我编写代码和测试时,一切似乎都运行良好,但我还看到了六种不同的方法来在 Internet 上设置数据库变量。如果这不正确,我想现在修复它。真正让我困惑的是,当我将我的应用程序推送到 Heroku 时,当数据库是 /usr/local/var/postgres 时,数据将如何推送到网络?或者这根本不会发生?在这一点上我是不是太困惑/累了?
采纳答案by Daniel Roseman
This is a simple matter of logic. You can't set the "default" key of the DATABASES dictionary before you have defined the dictionary itself.
这是一个简单的逻辑问题。在定义字典本身之前,您不能设置 DATABASES 字典的“默认”键。
Whether or not you set the default
parameterto dj_database_url
inside the call or as a separate DATABASE_URL
variable is irrelevant, especially as that won't even be used on Heroku as it will be overridden by environment variables.
无论你的设置default
参数来dj_database_url
调用内部或作为独立DATABASE_URL
变量是不相关的,尤其是作为甚至不会在Heroku上使用,因为它会被环境变量覆盖。
回答by moonstruck
This is documented on Heroku Devecenter
# Parse database configuration from $DATABASE_URL
import dj_database_url
# DATABASES['default'] = dj_database_url.config()
#updated
DATABASES = {'default': dj_database_url.config(default='postgres://user:pass@localhost/dbname')}
If you need Database connection poolingadd this bits too. More details
# Enable Connection Pooling
DATABASES['default']['ENGINE'] = 'django_postgrespool'