Home > Blockchain >  Heroku Python Local Environment Variables
Heroku Python Local Environment Variables

Time:01-02

Working on a heroku django project.

Goal: I want to run the server locally with same code on cloud too (makes sense).

Problem: Environments differ from a linux server (heroku) to a local PC windows system. Local environment variables differ from cloud Heroku config vars. Heroku config vars can be setup easily using the CLI heroku config:set TIMES=2.

While setting up local env vars is a total mess.

I tried the following in cmd: py -c "import os;os.environ['Times']=2" # To set an env var

Then ran py -c "import os;os.environ.get('Times','Not Found')" stdout: "Not Found".

After a bit of research it appeared to be that such env vars are stored temporarily per process/session usage.

Solution theory: Redirect os.environ to .env file of the root heroku project instead of the PC env vars. So I found this tool direnv perfect for Unix-like OSs but not available for Windows.

views.py code (runs perfect on cloud, sick on the local machine):

import os
import requests
from django.shortcuts import render
from django.http import HttpResponse
from .models import Greeting

def index(request):
    # get method takes 2 parameters (env_var_string,return value if var is not found)
    times = int(os.environ.get('TIMES',3))

    return HttpResponse('<p>'  'Hello! ' * times  '</p>')

def db(request):
    greeting = Greeting()
    greeting.save()
    greetings = Greeting.objects.all()
    return render(request, "db.html", {"greetings": greetings})

Main Question: Is there a proper way to hide secrets locally in windows and access them by os.environ['KEY']?

Another solution theory: I was wondering if a python virtual environment has it's own environment variables. If yes i activate a venv locally without affecting the cloud. Therefore os.environ['KEY'] is redirected to the venv variables. Again it's just a theory.

CodePudding user response:

You can use environment variables which you can get via os.environ['KEY'].
The same code will work on both local development and on Heroku.

On Heroku define these variables using ConfigVars heroku config:set KEY=val while locally (on Windows for example) define the same variables in an .env file (use dotenv to load them). The .env file is never committed with the source code.

  • Related