P Y
P Y

Reputation: 21

Set Json file as an environment variable in heroku

We are using Google classifier(AI and machine learning product of google) in our application for one of the use case.Google needs json file which contains credentials to access classifier related things.We are trying to set this json file in environment variables on heroku.

We want to set JSON file(.json) in environment variables on Heroku. How we can achieve above scenario?

Upvotes: 2

Views: 1351

Answers (1)

Micah Smith
Micah Smith

Reputation: 4453

  1. Encode the json file as a string
import json
with open('service_account.json', 'r') as f:
    info = json.load(f)
service_account_info = json.dumps(info)
  1. Dump the string to your .env file for example
with open('.env', 'a') as f:
    f.write(f'GOOGLE_SERVICE_ACCOUNT={service_account_info}')
  1. Push the .env values to heroku, for example using invoke to run commands and honcho to parse the env file. (Can also use subprocess and python-dotenv, etc.)
from invoke import run
from honcho.environ import parse
with open('.env', 'r') as f:
    env = parse(f.read())
cmd = 'heroku config:set ' + ' '.join(
    f'{key}=\'{value}\''
    for key, value in env.items()
)
run(cmd)
  1. Throw away (metaphorically) the json file and only use the envvars.
import json
service_account_info = json.loads(getenv('GOOGLE_SERVICE_ACCOUNT'))
# do something with service_account_info!

Upvotes: 1

Related Questions