Fawwaz Yusran
Fawwaz Yusran

Reputation: 1480

Django + Heroku: KeyError when accessing Heroku's config vars

I'm trying to get all the environment variables from Heroku's config vars by following this page. So in settings.py I wrote:

import os

from dotenv import load_dotenv
from boto.s3.connection import S3Connection
# ...
load_dotenv(verbose=True)
# ...
s3 = S3Connection(os.environ['SECRET_KEY'],
                  os.environ['DATABASE_URL'],
                  os.environ['SENDGRID_API_KEY'])
SECRET_KEY = os.getenv('SECRET_KEY')
# ...

if os.environ.get('DEBUG') is None:
    DEBUG = False
else:
    DEBUG = True
# ...
# Sending emails
SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY')

EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey'
EMAIL_HOST_PASSWORD = SENDGRID_API_KEY
EMAIL_PORT = 587
EMAIL_USE_TLS = True
# ...

I want to have a local .env that contains those vars, and use Heroku's config vars in production. But when I deploy, I get an Application Error, and this is the result of heroku logs --tail:

2020-02-19T04:09:27.730183+00:00 app[web.1]: File "/app/smart_toilet_system/settings.py", line 34, in <module>
2020-02-19T04:09:27.730183+00:00 app[web.1]: os.environ['SENDGRID_API_KEY'])
2020-02-19T04:09:27.730183+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/boto/s3/connection.py", line 194, in __init__
2020-02-19T04:09:27.730184+00:00 app[web.1]: validate_certs=validate_certs, profile_name=profile_name)
2020-02-19T04:09:27.730184+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/boto/connection.py", line 502, in __init__
2020-02-19T04:09:27.730185+00:00 app[web.1]: self.port = PORTS_BY_SECURITY[is_secure]
2020-02-19T04:09:27.730185+00:00 app[web.1]: KeyError: '<SENDGRID_API_KEY>'
2020-02-19T04:09:27.730911+00:00 app[web.1]: [2020-02-19 04:09:27 +0000] [10] [INFO] Worker exiting (pid: 10)
2020-02-19T04:09:27.838786+00:00 app[web.1]: [2020-02-19 04:09:27 +0000] [4] [INFO] Shutting down: Master
2020-02-19T04:09:27.839030+00:00 app[web.1]: [2020-02-19 04:09:27 +0000] [4] [INFO] Reason: Worker failed to boot.
2020-02-19T04:09:28.081341+00:00 heroku[web.1]: State changed from up to crashed
2020-02-19T04:09:28.062132+00:00 heroku[web.1]: Process exited with status 3

What is causing this error? Is it to do with escaping special characters?

Upvotes: 0

Views: 1114

Answers (1)

Ashish
Ashish

Reputation: 459

I think you are not able to access them because they are not in that environment(it means that they are not in your normal environment). For accessing those .env config variables you can use python-decouple(install it) and access those variable like this:

from decouple import config
s3 = S3Connection(config('SECRET_KEY'),
              config('DATABASE_URL'),
              config('SENDGRID_API_KEY'))

I hope this will woek for you

Upvotes: 0

Related Questions