Forums

Setting environment variables (Flask configuration)

I'm probably missing something very obvious because I've googled this and haven't found any answers at all.

On heroku and openshift, I've been using environment variables for configuration to set stuff like my database uri.

Is it possible keep using the same pattern on pythonanywhere ?

It's actually not all that obvious, so don't worry :-) I'm assuming you need these for configuring your web app?

We don't have anything built in to support that, but if your code uses environment variables to configure itself, the best way is probably to set them in the WSGI file that starts your web app. For example, if you use the variable DB_HOST to set the database host for khalilelkouhen.pythonanywhere.com, just put this near the start of the file /var/www/khalilelkouhen_pythonanywhere_com_wsgi.py:

import os
os.environ['DB_HOST'] = 'the host name'

Thank you.

For anyone else with this problem, I've tried to write up a quick guide to setting up environment variables: https://help.pythonanywhere.com/pages/environment-variables-for-web-apps

How can we use boolean variables here?

In wsgi.py

os.environ['DJANGO_SETTINGS_MODULE'] = 'ontrack.settings'
os.environ["SECRET_KEY"] = "SOMEKEY@#))ASDJASDSD()DADAS"
os.environ["DEBUG1"] = False
os.environ["DATABASE_URL"] = 'prod-db.sqlite3'

I get an error where I set my DEBUG variable to the boolean False, but my settings will only work like that. I can hack around it for now, but was wondering if there's a way to include boolean variables here.

TypeError: must be string, not bool
File "/var/www/ontrack_pythonanywhere_com_wsgi.py", line 10, in <module>
os.environ["DEBUG1"] = False

Thanks!

maybe try reloading your webapp? and also is it just debug1 that is error-ing? what if you try some different environment variable names?

I am having the same issue with setting setting os.environ["DEBUG"] = False. Same error that it must be a string. Is there a way to set this up as a bool so that it will load properly? Or is there a better way to set this so that I don't need to manually change every time I make code changes?

thanks!

Environment variables are always strings. You cannot set environment variables to any other Python types. If you're using environment variables to configure your web app, then either you or the framework you're using needs to translate the environment variable into a form that can be used by your web framework.

Thanks....For some reason I didn't think to just convert it in settings.py (using Django). That sorted me out.

OK -- glad it's sorted out!