29
loading...
This website collects cookies to deliver better user experience
python-dotenv
demo/__init__.py
demo/settings.py
.env
.flaskenv
run.py
pipenv
, so I can do this all in one step:pipenv install flask python-dotenv
pipenv shell
demo/init.py
, we'll need to create the basics of a Flask app, which means importing Flask, creating a application factory function (create_app)
, and instantiating Flask. Here's the code to do this.# demo/__init__.py
from flask import Flask
def create_app():
app = Flask(__name__)
return app
# demo/__init__.py
from flask import Flask
def create_app():
app = Flask(__name__)
@app.route('/')
def index():
return '<h1>Hey There!</h1>'
return app
flask run
export FLASK_APP=demo
python-dotenv
and we want to avoid the inconvenience of using the command line, we'll have this load automatically by putting it in one of our dot files..env
and .flaskenv
. We want to use .flaskenv
for any Flask CLI configuration commands and use .env for our app configuration.
.flaskenv file.
#.flaskenv
FLASK_APP=demo
flask run
.flaskenv
file.#.flaskenv
FLASK_APP=demo
FLASK_ENV=development
flask run
#.flaskenv
FLASK_APP=demo
FLASK_ENV=development
FLASK_RUN_PORT=8080
FLASK_RUN_EXTRA_FILES=config.yml:README.md
#.env
SECRET_KEY=topsecretkey
API_KEY=donotsharethisapikeywithanyone
.flaskenv
file, the variables in .env aren't meant to work for us automatically. Instead, we need to load them into our app. For that, we'll use the settings.py file.#demo/settings.py
from os import environ
#demo/settings.py
from os import environ
SECRET_KEY = environ.get('SECRET_KEY')
API_KEY = environ.get('API_KEY')
# demo/__init__.py
from flask import Flask
def create_app():
app = Flask(__name__)
app.config.from_pyfile('settings.py')
@app.route('/')
def index():
return '<h1>Hey There!</h1>'
return app
# demo/__init__.py
from flask import Flask
def create_app():
app = Flask(__name__)
app.config.from_pyfile('settings.py')
@app.route('/')
def index():
return f'API_KEY = { app.config.get("API_KEY") }'
return app
pipenv install gunicorn
#run.py
from demo import create_app
app = create_app()
gunicorn run:app
#run.py
from demo import create_app
from dotenv import load_dotenv
load_dotenv('.env') #the path to your .env file (or any other file of environment variables you want to load)
app = create_app()