Home > Blockchain >  Add a variable in a .env file in python
Add a variable in a .env file in python

Time:09-03

I have a .env file in my application and Im trying to run a script in docker. When docker reaches the entrypoint.sh it runs python manage.py runscript tryouts getting a count and then it goes like this (jwt_token is generated earlier in the script):

ChirpStackURL = os.environ['CHIRPSTACK']

def checkNetworks(jwt_token):
    url = ChirpStackURL   '/api/network-servers?limit=10'
    res = requests.get(url, headers = {"Authorization": jwt_token})
    count = res.json()['totalCount']
    if count == '1' :
        return res.json()['result'][0]['id']
    else: 
        return False

and then on my function i want to add the result as an enviromental variable so i can access it later on new requests.

    networkServerID = checkNetworks(jwt_token)
    if not networkServerID:
        print('success')
    else:
      'export to .env file'
      'NETWORK_ID = networkServerID'

sample = os.environ['NETWORK_ID']

How do i do that ?

CodePudding user response:

An envfile is just a text file with key=value lines, so append the new variable into it:

with open("path/to/my/.env", "a") as envfile:
    envfile.write(f"NETWORK_ID = {networkServerId}\n")
  • Related