简体   繁体   中英

Add a variable in a .env file in python

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?

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM