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.
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.
Install Python.
Create a New Project Directory:
mkdir myproject
cd myproject
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.
Activate the Virtual Environment: source venv/bin/activate.
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
Deactivate the Virtual Environment: deactivate. This will return you to your global Python environment.
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.
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.
"""
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
"""
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