user2859829
user2859829

Reputation: 137

Setting environment variables for Heroku / python app in Ubuntu

I've read a few how-tos but still struggling with this. In my app I was previously just pulling in my secret keys from a .py file that was in my folder system (which is not best practice). Instead I'd like to use the os module to get my secret keys in my dev environment (and do the same in heroku eventually), similar to the code below:

import os    
OAUTH_TOKEN = os.getenv('OAUTH_TOKEN')

I've read that I need to add my actual OAUTH_TOKEN to the .profile file for this to work.

OAUTH_TOKEN = 'mysecretkey'

However, when I got to run the first snippet of code above and attempt to print the OAUTH_TOKEN variable I get nothing in return. I also added my key to the .bashsrc file as well as some other websites said to do this.

What is going on and why can't I retrieve my secret key this way? What am I missing?

Upvotes: 0

Views: 747

Answers (1)

Gitau Harrison
Gitau Harrison

Reputation: 3517

To retrieve your secret keys while working on a Python-Flask app, you will need to install python-dotenv. This package will help with loading of secret or even runtime environment variables.

(venv)$ pip3 install python-dotenv

In your secret keys file, say, .env, initialize your secret environment variables:

# .env

OAUTH_TOKEN='<your-secret-oauth-token>'

To load OAUTH_TOKEN, use load-dotenv from dotenv:

# config.py

import os
from dotenv import load_dotenv

load_dotenv('.env')

class Config(object):
    OAUTH_TOKEN = os.getenv('OAUTH_TOKEN') 
    # or OAUTH_TOKEN = os.environ.get('OAUTH_TOKEN')

In your terminal, try to retrieve the value of OAUTH_TOKEN as follows. I am using flask shell command rather than python3:

# start your python interpreter in the context of your application
(venv)$ flask shell

>>> from app import Config
>>> print(app.config['OAUTH_TOKEN']))

# Your token should be printed here

The assumption above is that in your application instance, say __init__.py file, you have imported Config.

# __init__.py

from flask import Flask
from config import Config

app = Flask(__name__)
app.config.from_object(Config)

# ...

Upvotes: 1

Related Questions