Accessing environment variable in azure web app (python)

Ayan Usmani 171 Reputation points
2024-05-15T06:36:48.9+00:00

I have a django application where I am trying to fetch the environment variables required in the app. (I have refered this blog)

But still I am not able to fetch the environment values.

This is the code block for fetching the db connection from the blog:

conn_str = os.environ.get("AZURE_POSTGRESQL_CONNECTIONSTRING")
conn_str_params = {
    pair.split("=")[0]: pair.split("=")[1] for pair in conn_str.split(" ")
}
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": conn_str_params.get("dbname"),
        "HOST": conn_str_params.get("host"),
        "USER": conn_str_params.get("user"),
        "PASSWORD": conn_str_params.get("password"),
    }
}

DB connection string are also not getting fetched (that is why I tried explicitly specifying DB related variables as shown in the screenshot which also did not worked).

Azure SQL Database
Azure App Service
Azure App Service
Azure App Service is a service used to create and deploy scalable, mission-critical web apps.
7,177 questions
0 comments No comments
{count} votes

Accepted answer
  1. TP 81,981 Reputation points
    2024-05-15T07:39:07.7733333+00:00

    Hi,

    First, whenever you make a change to environment variables or connection strings via portal please restart your webapp after clicking Apply.

    Second, do you have your connection string under Settings -- Environment variables -- Connection strings tab, or App settings tab? If you have it under Connection strings tab with type PostgreSQL it will be injected into your app with prefix of POSTGRESQLCONNSTR_

    For example, say you have a connection string in portal named MYCONNECTIONSTRING1. In your web app, it would show up as POSTGRESQLCONNSTR_MYCONNECTIONSTRING1 so in your python code you would use code similar to below:

    conn_str = os.environ.get("POSTGRESQLCONNSTR_MYCONNECTIONSTRING1")
    
    

    For troubleshooting purposes you may use SSH to connect to the worker and check the list of environment variables and their values. In the portal, navigate to your web app -- Development tools -- SSH blade, then click Go on right to launch session. At prompt you may type env to see list of variables.

    Please click Accept Answer and upvote if the above was helpful.

    Thanks.

    -TP

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful