JustToThePoint English Website Version
JustToThePoint en español
JustToThePoint in Thai

Managing Configuration with python-dotenv. Access news. Security with passwords.

And there are never really endings, happy or otherwise. Things keep going on, they overlap and blur, your story is part of your sister’s story is part of many other stories, and there is no telling where any of them may lead. Everything turns in circles and spirals with the cosmic heart until infinity.

Create a new Python project & Migrating

Creating a clean, new Python project with a virtual environment (venv) is an excellent practice for managing dependencies and ensuring that your project's environment is isolated from other projects and the global Python environment.

  1. Install Python.

  2. Create a New Project Directory:

    mkdir myproject
    cd myproject
    
  3. Create a Virtual Environment: python3 -m venv venv. It is named venv and it is within your project directory, containing a fresh, isolated Python environment.

  4. Activate the Virtual Environment: source venv/bin/activate.

  5. Install Packages using pip, and they will be installed and contained in your project’s virtual environment isolated from the global Python environment, e.g., pip install requests

  6. Deactivate the Virtual Environment: deactivate. This will return you to your global Python environment.

  7. Managing Dependencies: pip freeze > requirements.txt. If you want to migrate to a new computer, you can do so by creating the project directory (mkdir project, cd myproject), the virtual environment (python3 -m venv venv), activate the virtual environment (source venv/bin/activate), copy your source files, .env, .gitignore, and assets, and then install your required packages with pip install -r requirements.txt.

The IndentationError: unindent does not match any outer indentation level in Python occurs when the spaces or tabs used for indentation in the code are inconsistent. You may want to convert spaces to tabs or viceversa by opening the Command Palette and selecting Convert Indentation to Spaces or Convert Indentation to Tabs.

Managing Configuration with python-dotenv

python-dotenv reads key,value pairs from a file .env and adds them to environment variables. Storing configuration in the environment separate from code is based on The Twelve-Factor App methodology.

The Twelve-Factor App methodology emphasizes the use of environment variables for configuration rather than hardcoding them into the codebase. This approach offers several benefits: portability (environment variables can vary between deployment environment without requiring changes to the codebase), security (sensitive information such as API keys, passwords, etc., can be kept out of the codebase and managed separately), flexibility (configuration changes can be made without modifying the code), scalability (as the application grows, managing configuration through environment variables becomes more efficient and manageable).

As was previously stated, python-dotenv is a Python library that facilitates this approach by reading key-value pairs from a .env file and adding them to the environment variables.

  1. Install the library: pip install python-dotenv
  2. Create a .env file in your project directory or an asset directory (organization is key) and add the configuration variables in the format KEY=VALUE.
  3. Use python-dotenv() to load the variables into your application.
  4. Access the variables using os.getenv, e.g., api_key = os.getenv(“API_KEY”).

Displaying progress of tasks using the rich library

	"""
	File: util.py
	Author: Máximo Núñez Alarcón
	Description: This script defines a function to display the progress of a task using a progress bar.
	Usage: Import the my_progress function and call it with the name of the task as an argument.
	Dependencies: rich, time, dotenv
	"""

	from rich.progress import Progress # It is used for displaying progress bars
	import time # It is used for adding delays
	from dotenv import load_dotenv 
	''' It reads key-value pairs from a .env file in your Python's root folder and can set them as environment variables. 
	If your application takes its configuration from environment variables, launching it in development is not practical because you have to set those environment variables yourself.
	To help you with that, you can add Python-dotenv to your application to make it load the configuration from a .env file. 
	It requires to install: pip install python-dotenv.''' 
	import os # This module provides a way of using operating system dependent functionality. We are going to use it for accessing environment variables 

	# Define a function to display progress of a task
	def my_progress(nameTask):
		load_dotenv() # Load environment variables from .env file
		totaltime = os.getenv("TIME_PROGRESS") 
		# Retrieve the total time for the progress from an environment variable TIME_PROGRESS. 
		# There is a line in the .env file: TIME_PROGRESS = 100
		# It's good practice to add .env to your .gitignore, especially if it contains secrets like a password.

		with Progress() as progress: # Create a progress bar
			task1 = progress.add_task("[red]" + nameTask + "... [/]", totaltime) # Add a task to the progress bar with the specified name
			while not progress.finished:  # Continue updating the progress bar until it's finished
				progress.update(task1, advance=0.9) # Update the progress bar by a certain amount (0.9 in this case)
				time.sleep(0.01) # Add a small delay to control the update frequency of the progress bar

How to get the latest news in Python. Security with your API_KEY

"""
File: news.py
Author: Máximo Núñez Alarcón
Description: This script fetches the latest headlines from the News API and prints them. 
News API is a simple HTTP REST API for searching and retrieving live articles from all over the web.
Usage: Run the script to fetch and display the latest headlines.
Dependencies: requests, os, my_progress (from util module)
"""

# Import necessary modules
import requests # It is used for making HTTP request
import os # It is used for accessing environment variables
from util import my_progress # It is used for displaying progress of the task

def fetch_headlines():
    """
    Fetches the latest headlines from the News API and prints them.
    """

    # Display progress of the task
    my_progress("Latest Headlines")

    # Retrieve News API key from environment variables
    # For security reason we will hide this key within environment variables on Linux
    # vi ~/.zshrc, export VARIABLE_NAME=VARIABLE_VALUE, in our particular case VARIABLE_NAME is News_API_KEY
    api_key = os.getenv("News_API_KEY")

    # Construct URL for fetching headlines
    url = f'https://newsapi.org/v2/top-headlines?country=us&apiKey={api_key}'

    # Make an HTTP request to fetch the news headlines
    response = requests.get(url)

    # Parse JSON response
    data = response.json()

    # Check if the response is successful
    if response.status_code == 200:
        i = 1
        # Iterate over the articles and print their titles and descriptions
        for article in data['articles']:
			title = article['title']
            description = article['description']
            if description is None:
                description = ""  # Replace None with an empty string
            print(f"{i} {title}: {description}")
            i += 1
    else:
        print("Failed to fetch headlines") # It prints an error message if request fails
Bitcoin donation

JustToThePoint Copyright © 2011 - 2024 Anawim. ALL RIGHTS RESERVED. Bilingual e-books, articles, and videos to help your child and your entire family succeed, develop a healthy lifestyle, and have a lot of fun. Social Issues, Join us.

This website uses cookies to improve your navigation experience.
By continuing, you are consenting to our use of cookies, in accordance with our Cookies Policy and Website Terms and Conditions of use.