gpt4 book ai didi

django - 在Heroku : Can I manually set environment variables in the . env文件上部署Django应用程序?我需要安装autoenv,heroku-config等工具吗?

转载 作者:行者123 更新时间:2023-12-04 04:38:37 30 4
gpt4 key购买 nike

我的目标:

我打算遵循“十二要素应用程序”方法在Heroku上构建Django应用程序。

介绍:

我正在遵循“Heroku上的Django入门”快速入门指南。目前,我具有以下目录结构:

~/Projects/
hellodjango_rep/
.env (empty)
.git
.gitignore
Procfile
requirements.txt
hellodjango/
manage.py
hellodjango/
__init__.py
settings/
urls.py
wsgi.py

我安装了django-toolbelt,创建了简单的Django应用程序,并在Procfile中启动了该过程...一切似乎都工作正常,但是当我为Heroku环境配置该应用程序并添加以下内容时,问题就开始了:
import dj_database_url
DATABASES['default'] = dj_database_url.config()

到我的settings.py文件的底部。

我将应用程序的存储库推送到Heroku,并通过 $ heroku open成功访问了浏览器中的应用程序,但在本地使用了: dj_database_url.config() 返回了一个空字典

本地:

OS X 10.8.4
点== 1.4.1
virtualenv == 1.10.1
virtualenvwrapper == 4.1.1
wsgiref == 0.1.2
在端口5432上运行的Postgres.app

环境变量:
mac-pol:hellodjango_rep oubiga$ python
>>> import os
>>> os.environ

{
'PROJECT_HOME': '/Users/oubiga/Projects'...
'PATH': '/usr/local/heroku/bin:/usr/local/share/python:/usr/local/bin:/Applications/Postgres.app/Contents/MacOS/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/git/bin'...
'HOME': '/Users/oubiga'...
'WORKON_HOME': '/Users/oubiga/Envs'...
'VIRTUALENVWRAPPER_HOOK_DIR': '/Users/oubiga/Envs'...
'PWD': '/Users/oubiga/Projects/hellodjango_rep'
}

hellodjango_venv:

的Django = = 1.5.2
dj-database-url == 0.2.2
dj-static == 0.0.5
django-toolbelt == 0.0.1
gunicorn == 18.0
psycopg2 == 2.5.1
静态== 0.4

这是我的wsgi.py文件中的内容:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hellodjango.hellodjango.settings")
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
application = Cling(get_wsgi_application())

这是我的manage.py文件中的内容:
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hellodjango.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)

这是我的Procfile中的内容:
web: gunicorn hellodjango.hellodjango.wsgi  

环境变量:
(hellodjango_venv)mac-pol:hellodjango_rep oubiga$ python hellodjango/manage.py shell
>>> import os
>>> os.environ


{
'PROJECT_HOME': '/Users/oubiga/Projects'...
'PATH': '/Users/oubiga/Envs/hellodjango_venv/bin:/usr/local/heroku/bin:/usr/local/share/python:/usr/local/bin:/Applications/Postgres.app/Contents/MacOS/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/git/bin',
'HOME': '/Users/oubiga'...
'WORKON_HOME': '/Users/oubiga/Envs'...
'VIRTUAL_ENV': '/Users/oubiga/Envs/hellodjango_venv'...
'VIRTUALENVWRAPPER_HOOK_DIR': '/Users/oubiga/Envs'...
'PWD': '/Users/oubiga/Projects/hellodjango_rep'...
'DJANGO_SETTINGS_MODULE': 'hellodjango.settings'
}

在Heroku上:

环境变量:
(hellodjango_venv)mac-pol:hellodjango_rep oubiga$ heroku run python hellodjango/manage.py shell
>>> import os
>>> os.environ

{
'DATABASE_URL': 'postgres://dbuser:dbpassword@ec2-184-73-162-34.compute-1.amazonaws.com:5432/dbname',
'HEROKU_POSTGRESQL_ORANGE_URL': 'postgres://dbuser:dbpassword@ec2-184-73-162-34.compute-1.amazonaws.com:5432/dbname',
'LIBRARY_PATH': '/app/.heroku/vendor/lib', 'PWD': '/app'...
'DJANGO_SETTINGS_MODULE': 'hellodjango.settings',
'PYTHONHOME': '/app/.heroku/python'...
'PYTHONPATH': '/app/'...
'DYNO': 'run.9068',
'LD_LIBRARY_PATH': '/app/.heroku/vendor/lib'...
'HOME': '/app', '_': '/app/.heroku/python/bin/python',
'PATH': '/app/.heroku/python/bin:/usr/local/bin:/usr/bin:/bin'...
}

(hellodjango_venv)mac-pol:hellodjango_rep oubiga$ heroku config
=== damp-dusk-5382 Config Vars
DATABASE_URL: postgres://dbuser:dbpassword@ec2-184-73-162-34.compute-1.amazonaws.com:5432/dbname
HEROKU_POSTGRESQL_ORANGE_URL: postgres://dbuser:dbpassword@ec2-184-73-162-34.compute-1.amazonaws.com:5432/dbname

研究:

在环境中存储配置:The Twelve-Factor App中的

@adamwiggins写道:

The twelve-factor app stores config in environment variables... Env vars are easy to change between deploys without changing any code; unlike config files.



dj_database_url.config()返回一个空对象:Heroku论坛中的

@chrisantonick回答:

... dj_database_url.config() gets the Postgres credentials from the Heroku environment variables. But, on your local machine, those variables aren't there. You have to put them in your /venv/bin/activate shell script... put the variables in there. something like
DATABASE_URL = "xxx"
export DATABASE_URL
For each thing it needs. Then... "deactivate"... and ..."activate" again to restart it.



Django和Heroku入门指南提出了错误配置错误:来自Heroku论坛的

@jwpe回答:

... dj-database-url is a great utility, as it allows you to use exactly the same settings.py code in your development and production environments, as recommended in the "12 factor app principles"... what dj_database_url.config() is doing is looking for the DATABASE_URL environment variable, and then parsing it into Django's preferred format... if you haven't manually created and promoted a postgres DB on Heroku, DATABASE_URL will not be present and the ImproperlyConfigured error will be raised. Setting the default for dj_database_url.config() as your local DB URL is one way to make sure that your application will work in a development environment. However, it is not necessarily the only way. Perhaps a better alternative is to manually set DATABASE_URL in your local .env file. Then, when running your app locally using Foreman, it will be loaded as an environment variable and dj_database_url will find it. So your .env would contain:


DATABASE_URL=postgres://user:pass@localhost/dbname

Meaning that in settings.py you would only need to have:


DATABASES['default']= dj_database_url.config()

...The advantage of using a local environment variable instead of a single, hard-coded default is that your code will run in any environment where the DATABASE_URL is set. If you change the name of your local DB, or want to run your code on a different dev machine, you only need to update your .env file instead of tinkering with settings.py.



如何管理生产/暂存/dev Django设置?:Heroku论坛中的

@rdegges回答:

... trying to get your application to behave in a way such that:

  • When you're running the app on your laptop, it uses your local Postgres server.
  • When you're running the app on your staging Heroku app, it uses the Postgres server addon.
  • When you're running the app on your production Heroku app, it uses the Postgres server addon.

The best way to accomplish this is by using environment variables!… Environment variables are the most elegant (and scalable) way to handle application configuration between different environments… Instead of having many settings files, define a single file: settings.py, and have it make use of environment variables to pull service information and credentials... On Heroku, you can set environment variables manually by running:

$ heroku config:set SOME_VARIABLE=some_value

... there's always Kenneth Reitz's great autoenv tool. This lets you define a simple .env file in your project directory… And each time you enter your project directory, those environment variables will be automatically set so that you don't have to do anything special! Just run your project and everything will work as expected: python
manage.py runserver



第一次尝试:

我在.env文件中手动设置了 DATABASE_URL: DATABASE_URL=postgres://dbuser:dbpassword@ec2-184-73-162-34.compute-1.amazonaws.com:5432/dbname
但是当我运行 $ foreman start命令时:
(hellodjango_venv)mac-pol:hellodjango_rep oubiga$ foreman start
17:25:39 web.1 | started with pid 319
17:25:39 web.1 | 2013-09-11 17:25:39 [319] [INFO] Starting gunicorn 18.0
17:25:39 web.1 | 2013-09-11 17:25:39 [319] [INFO] Listening at: http://0.0.0.0:5000 (319)
17:25:39 web.1 | 2013-09-11 17:25:39 [319] [INFO] Using worker: sync
17:25:39 web.1 | 2013-09-11 17:25:39 [322] [INFO] Booting worker with pid: 322

并尝试在浏览器 http://0.0.0.0:5000中打开我的应用程序:
17:26:59 web.1  | 2013-09-11 10:26:59 [322] [ERROR] Error handling request
17:26:59 web.1 | Traceback (most recent call last):
17:26:59 web.1 | File "/Users/oubiga/Envs/hellodjango_venv/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 131, in handle_request
17:26:59 web.1 | respiter = self.wsgi(environ, resp.start_response)
17:26:59 web.1 | File "/Users/oubiga/Envs/hellodjango_venv/lib/python2.7/site-packages/dj_static.py", line 59, in __call__
17:26:59 web.1 | return self.application(environ, start_response)
17:26:59 web.1 | File "/Users/oubiga/Envs/hellodjango_venv/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 236, in __call__
17:26:59 web.1 | self.load_middleware()
17:26:59 web.1 | File "/Users/oubiga/Envs/hellodjango_venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 53, in load_middleware
17:26:59 web.1 | raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e))
17:26:59 web.1 | ImproperlyConfigured: Error importing middleware django.contrib.auth.middleware: "dlopen(/Users/oubiga/Envs/hellodjango_venv/lib/python2.7/site-packages/psycopg2/_psycopg.so, 2): Library not loaded: @loader_path/../lib/libssl.1.0.0.dylib
17:26:59 web.1 | Referenced from: /Users/oubiga/Envs/hellodjango_venv/lib/python2.7/site-packages/psycopg2/_psycopg.so
17:26:59 web.1 | Reason: image not found"

但是, dj_database_url.config()返回:
{
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'dbname',
'HOST': 'ec2-23-21-196-147.compute-1.amazonaws.com',
'USER': 'dbuser',
'PASSWORD': 'dbpassword',
'PORT': 5432
}

第二次尝试:

我在更改主机的.env文件中手动设置了 DATABASE_URL。我将“ec2-184-73-162-34.compute-1.amazonaws.com:5432”替换为“localhost:5000”。 $ deactivate,然后再次是 $ workon hellodjango_venv
DATABASE_URL=postgres://dbuser:dbpassword@localhost:5000/dbname
但是,当我运行 $ foreman start命令时:
(hellodjango_venv)mac-pol:hellodjango_rep oubiga$ foreman start
17:38:41 web.1 | started with pid 687
17:38:41 web.1 | 2013-09-11 17:38:41 [687] [INFO] Starting gunicorn 18.0
17:38:41 web.1 | 2013-09-11 17:38:41 [687] [INFO] Listening at: http://0.0.0.0:5000 (687)
17:38:41 web.1 | 2013-09-11 17:38:41 [687] [INFO] Using worker: sync
17:38:41 web.1 | 2013-09-11 17:38:41 [690] [INFO] Booting worker with pid: 690

并尝试在浏览器 http://0.0.0.0:5000中打开我的应用程序:
17:38:46 web.1  | 2013-09-11 10:38:46 [690] [ERROR] Error handling request
17:38:46 web.1 | Traceback (most recent call last):
17:38:46 web.1 | File "/Users/oubiga/Envs/hellodjango_venv/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 131, in handle_request
17:38:46 web.1 | respiter = self.wsgi(environ, resp.start_response)
17:38:46 web.1 | File "/Users/oubiga/Envs/hellodjango_venv/lib/python2.7/site-packages/dj_static.py", line 59, in __call__
17:38:46 web.1 | return self.application(environ, start_response)
17:38:46 web.1 | File "/Users/oubiga/Envs/hellodjango_venv/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 236, in __call__
17:38:46 web.1 | self.load_middleware()
17:38:46 web.1 | File "/Users/oubiga/Envs/hellodjango_venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 53, in load_middleware
17:38:46 web.1 | raise exceptions.ImproperlyConfigured('Error importing middleware %s: "%s"' % (mw_module, e))
17:38:46 web.1 | ImproperlyConfigured: Error importing middleware django.contrib.auth.middleware: "dlopen(/Users/oubiga/Envs/hellodjango_venv/lib/python2.7/site-packages/psycopg2/_psycopg.so, 2): Library not loaded: @loader_path/../lib/libssl.1.0.0.dylib
17:38:46 web.1 | Referenced from: /Users/oubiga/Envs/hellodjango_venv/lib/python2.7/site-packages/psycopg2/_psycopg.so
17:38:46 web.1 | Reason: image not found"

这次, dj_database_url.config()返回了:
{
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'dbname',
'HOST': 'localhost',
'USER': 'dbuser',
'PASSWORD': 'dbpassword',
'PORT': 5000
}

第三次尝试:

我安装了autoenv mac-pol:~ oubiga$ pip install autoenv肯尼思·雷茨(Kenneth Reitz)在这张 Cookbook中写道:
use_env() {
typeset venv
venv="$1"
if [[ "${VIRTUAL_ENV:t}" != "$venv" ]]; then
if workon | grep -q "$venv"; then
workon "$venv"
else
echo -n "Create virtualenv $venv now? (Yn) "
read answer
if [[ "$answer" == "Y" ]]; then
mkvirtualenv "$venv"
fi
fi
fi
}

在我的.bashrc文件中。

我运行 $ foreman start命令:
(hellodjango_venv)mac-pol:hellodjango_rep oubiga$ foreman start
18:11:57 web.1 | started with pid 1104
18:11:57 web.1 | 2013-09-11 18:11:57 [1104] [INFO] Starting gunicorn 18.0
18:11:57 web.1 | 2013-09-11 18:11:57 [1104] [INFO] Listening at: http://0.0.0.0:5000 (1104)
18:11:57 web.1 | 2013-09-11 18:11:57 [1104] [INFO] Using worker: sync
18:11:57 web.1 | 2013-09-11 18:11:57 [1107] [INFO] Booting worker with pid: 1107

并尝试在浏览器中打开我的应用程序 http://0.0.0.0:5000:它起作用了!
^CSIGINT received
18:12:06 system | sending SIGTERM to all processes
18:12:06 web.1 | 2013-09-11 11:12:06 [1107] [INFO] Worker exiting (pid: 1107)
SIGTERM received
18:12:06 web.1 | 2013-09-11 18:12:06 [1104] [INFO] Handling signal: int
18:12:06 web.1 | 2013-09-11 18:12:06 [1104] [INFO] Shutting down: Master
18:12:06 web.1 | exited with code 0

但是,dj_database_url.config()再次返回一个空字典。

作为最终尝试:

我对 python manage.py runserver命令感到好奇,并检查了一下。
(hellodjango_venv)mac-pol:hellodjango_rep oubiga$ foreman run python hellodjango/manage.py runserver
Validating models...

0 errors found
September 11, 2013 - 18:42:37
Django version 1.5.2, using settings 'hellodjango.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

并尝试在浏览器中打开我的应用程序 http://127.0.0.1:8000/:它不起作用!

引发了 ImportError: No module named hellodjango.urls

我用 ROOT_URLCONF = 'hellodjango.hellodjango.urls'替换了settings.py文件中的 ROOT_URLCONF = 'hellodjango.urls',它终于起作用了。

如预期的那样,dj_database_url.config()返回了一个空字典。

所以:

现在,我有点不知所措。恐怕我误解了一些核心概念。
  • 使用gunicorn代替Django开发服务器有什么意义?
  • 为什么dj_database_url.config()有时返回完整填充的字典,有时却返回空的字典?
  • 我可以在.env文件中手动设置环境变量吗?我需要安装autoenv,heroku-config等工具吗?

  • 先感谢您。

    最佳答案

    我也陷入了postgres的困境,这是我在settings.py中添加本地设置的方法:

    DATABASES = {
    'default': dj_database_url.config(default='postgres://<user>:<password>@<host>/<dbname>')
    }

    当然,您必须按照postgres步骤创建数据库。
    解决方案来自 https://discussion.heroku.com/t/dj-database-url-config-is-returning-an-empty-object/55/9

    关于django - 在Heroku : Can I manually set environment variables in the . env文件上部署Django应用程序?我需要安装autoenv,heroku-config等工具吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18753270/

    30 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com