Activity 37: Python Flask .env and gitignore
To complete this activity on using .env
and .gitignore
in a Python Flask project, set up a secure environment configuration and then push the project to GitHub:
Set Up a New Flask Project
Create a new project folder:
mkdir salibay_env_gitignore cd salibay_env_gitignore
Initialize a Flask project: Create a virtual environment and install Flask.
python -m venv venv pip install Flask
Create the main app file: Create a file named
app.py
and add the following code:from flask import Flask import os app = Flask(__name__) app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'defaultsecret') @app.route('/') def home(): return 'Hello, Flask with .env!' if __name__ == '__main__': app.run(debug=True)
Set Up the .env
File
Install Python Dotenv:
pip install python-dotenv
Create a
.env
file in the project directory and add the following line:SECRET_KEY="secret_key"
Load the .env file in app.py by adding the following at the top of
app.py
:from dotenv import load_dotenv load_dotenv()
Create a .gitignore
File
In the root of your project, create a
.gitignore
file and add the following lines to ignore sensitive files and the virtual environment:.env venv/ __pycache__/ *.pyc *.pyo
Initialize Git and Commit
Initialize a Git repository:
git init
Add and commit files:
git add . git commit -m "Initial commit with .env and .gitignore"
Create a GitHub Repository and Push
Create a new repository on GitHub named
surname_env_gitignore
.Add the remote origin and push:
git remote add origin https://github.com/MonetForProgrammingPurposes/nicolas_env_gitignore.git git branch -M main git push -u origin main