João Ramires
João Ramires

Reputation: 773

How to access Environment Variables in Django with Django Environ?

I'm a Node developer but I need to create a Django app (i'm totally beginner in Django). I need to read some data from an API but ofc, I shouldn't hardcode the API url.

So having API_BASE_URL=api.domain.com in my .env file, in Node I would access the variables in my functions this way:

import ('dotenv/config');
import axios from 'axios';

baseUrl = process.env.API_BASE_URL;

function getApiData() {
    return axios.get(baseUrl);
}

So how would be the Python/Django version of it?

Saying I have the function bellow:

import ???

def get_api_data():
    url = ????

Upvotes: 1

Views: 2404

Answers (2)

F.NiX
F.NiX

Reputation: 1505

import environ

# reading .env file
environ.Env.read_env()

def get_api_data():
    url = env('API_BASE_URL')

Upvotes: 2

Daniel
Daniel

Reputation: 3527

Let's say you have a .env file saved in the same directory as your manage.py file.

You can then go to settings.py and do:

from decouple import config

API_BASE_URL = config('API_BASE_URL')

Assuming your .env file looks like:

API_BASE_URL='some.url'

Upvotes: 2

Related Questions