Activity 37: Python Flask .env and gitignore (SIA2)

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

  1. Create a new project folder:

     mkdir nicolas_env_gitignore
     cd nicolas_env_gitignore
    
  2. Initialize a Flask project: Create a virtual environment and install Flask.

     python -m venv venv
     pip install Flask
    
  3. 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

  1. Install Python Dotenv:

     pip install python-dotenv
    
  2. Create a .env file in the project directory and add the following line:

     SECRET_KEY="secret_key"
    
  3. 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

  1. 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

  1. Initialize a Git repository:

     git init
    
  2. Add and commit files:

     git add .
     git commit -m "Initial commit with .env and .gitignore"
    

Create a GitHub Repository and Push

  1. Create a new repository on GitHub named surname_env_gitignore.

  2. 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
    

REPOSITORY

https://github.com/MonetForProgrammingPurposes/nicolas_env_gitignore.git