Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a list/tuple into an environment variable for Django

anybody know how I can pass a list into an environment variable? At the moment I am trying to put a list of codes into my settings.py file.

I have this in my .env file:

ALLOWED_CODES='AB01', 'AB02'

In my settings.py this is what I have:

ALLOWED_CODES = [os.environ.get('ALLOWED_POSTCODES')]

If run docker-compose config it is parsed as:

ALLOWED_CODES: '''AB01'', ''AB02'''

What I want is for it to return the exact list defined in the .env file.

like image 766
Rutnet Avatar asked Dec 03 '18 18:12

Rutnet


People also ask

Can environment variables be a list?

There are multiple ways to list or display an environment variable in Linux. We can use the env, printenv, declare, or set command to list all variables in the system. In this tutorial, we'll explain how to list environment variables in Linux.

How do you pass an environment variable?

In the User variables section, select the environment variable you want to modify. Click Edit to open the Edit User Variable dialog box. Change the value of the variable and click OK. The variable is updated in the User variables section of the Environment Variables dialog box.

Can an environment variable be an array?

An array of environment variables. Each element of the array is the value in the current environment and the index is the name of the environment variable.


1 Answers

os.environ.get('ALLOWED_POSTCODES') will always return a string. It's up to you to convert that into a list.

ALLOWED_CODES='AB01', 'AB02'

If you could change your .env file to

ALLOWED_CODES=AB01,AB02

then you could do

ALLOWED_CODES = os.environ.get('ALLOWED_POSTCODES').split(",")

You could probably parse the current value into your required list, but the string manipulation would be harder.

You might want to use a package that can handle .env files for you, for example django-environ.

like image 116
Alasdair Avatar answered Nov 05 '22 05:11

Alasdair