Credential Management
Credential Management
To interact with the Google Custom Search API, the Eternity library requires a Google API Key and a Search Engine ID (CX).
For security reasons, you should never hardcode these credentials directly into your source code. Hardcoding secrets increases the risk of accidental exposure via version control systems like Git. Instead, follow these industry-standard best practices.
Using Environment Variables
Environment variables are the recommended way to handle secrets in both local development and production environments.
-
Set the variables in your terminal:
export GOOGLE_API_KEY='your_api_key_here' export GOOGLE_ENGINE_ID='your_engine_id_here' -
Access them in your Python code:
Use the built-in
osmodule to retrieve these values and pass them to theEternityconstructor.import os from eternity import Eternity # Retrieve credentials from environment variables api_key = os.getenv("GOOGLE_API_KEY") engine_id = os.getenv("GOOGLE_ENGINE_ID") # Initialize the client eternity = Eternity(api_key=api_key, engine_id=engine_id)
Using a .env File
For local development, managing multiple environment variables can be simplified using a .env file and the python-dotenv library.
-
Create a
.envfile in your project root:GOOGLE_API_KEY=your_api_key_here GOOGLE_ENGINE_ID=your_engine_id_here -
Load the variables in your script:
import os from dotenv import load_dotenv from eternity import Eternity load_dotenv() # This loads variables from the .env file into os.environ client = Eternity( api_key=os.getenv("GOOGLE_API_KEY"), engine_id=os.getenv("GOOGLE_ENGINE_ID") )
Security Checklist
To keep your credentials safe, always adhere to the following:
- Add
.envto.gitignore: Ensure your secret files are never committed to your repository. - Restrict API Key Scope: In the Google Cloud Console, restrict your API key to only allow requests from your specific IP addresses or to only use the Custom Search API.
- Rotate Keys Regularly: Periodically regenerate your API keys to minimize the impact of potential leaks.
- Use Secret Managers: For production deployments (e.g., AWS, GCP, or Azure), use dedicated secret management services instead of plaintext environment variables where possible.