2.2 — Environment Variables — Secrets Ko Safe Rakhna
Environment Variables — Secrets Ko Safe Rakhna
Alright, let's do this.
MODULE 2: Python Bot Architecture — Ek Professional Bot Ka Skeleton
LESSON 2.2: Environment Variables — Secrets Ko Safe Rakhna
Assalam-o-Alaikum, bot masters!
Chalo bachon, aaj ki class shuru karte hain. Suno ghौर se, kyun ke yeh lesson shayad is poore course ka sab se important lesson hai. Agar yeh samajh nahi aaya, tou tumhara bot banne se pehle hi tumhara bank account khaali ho sakta hai. No joke.
Aaj hum seekhenge ke apne bot ke "secrets" — API keys, private keys, passwords — ko professional tareeqay se kaise manage karte hain.
The Problem: Hardcoding Kyun Itna Bara Gunah Hai?
Dekho, main ne itne saare junior developers dekhe hain, khaas kar Pakistan mein, jo yeh galti karte hain. Woh apni API key direct code mein daal dete hain:
# DANGEROUS - KABHI BHI AISA MAT KARNA!
GEMINI_API_KEY = "sk-12345abcdefghijklmnopqrstuvwxyz"
def get_prediction(market_question):
# ... code to call Gemini API using the key ...
pass
Lagta hai na ke aasaan hai? Chale ga bhi. Problem tab aati hai jab tum yeh code GitHub pe push karte ho. Tum ne code public repository mein push kiya aur so gaye. Subah uthe tou Google Cloud ya OpenAI se email aayi hui hai ke aapka $5000 ka bill ban gaya hai. Kyun? Kyunke poori dunya mein bots hain jo GitHub ko scan karte rehte hain aisi leaked keys ke liye. Jaise hi unko key milti hai, woh usay use kar ke crypto mining ya doosre kaam shuru kar dete hain, aur bill tumhare naam pe phat'ta hai.
Your API key is like your ghar ki chaabi. Aap har kisi ko nahi dete phirtay, aur na hi darwazay pe likh ke chortay ho. Code mein key daalna darwazay pe chaabi likhne ke barabar hai.
Hamare Polymarket Oracle Bot mein, hamare paas kaafi saare secrets honge:
- LLM API Keys: Gemini, Anthropic (Haiku, Sonnet) ke liye.
- Polymarket Private Key: Actual trades execute karne ke liye wallet ki key.
- Database Credentials: Agar hum trade history database mein save kar rahe hain.
- Exchange API Keys: Agar hum Binance ya doosri exchanges se data le rahe hain.
In sab ko code se bahar rakhna hai. Period.
The Solution: The .env File — The Secret Tijori
The professional solution is a simple text file. Iska naam hum rakhte hain .env. Yeh file tumhare project ke root folder mein pari hoti hai aur is mein hum apne saare secrets KEY=VALUE format mein likhte hain.
For example, hamare bot ke liye, ek .env file aisi dikhegi:
.env file:
# Yeh file ek simple text file hai. Comments # se shuru hote hain.
# IMPORTANT: Yeh file KABHI BHI GitHub pe commit nahi karni.
# LLM Keys
GEMINI_API_KEY=your_super_secret_gemini_key_here
ANTHROPIC_API_KEY=your_anthropic_api_key_goes_here
# Wallet/Trading Keys
POLYMARKET_PRIVATE_KEY=0xYourWalletPrivateKeyForSigningTransactions
# Bot Configuration
ORACLE_LIVE_TRADING=false
ORACLE_CAPITAL=30
Simple, saaf suthra. Ab sab se zaroori kaam. Tumhe Git ko batana hai ke bhai, is file ko ignore karna hai. Is ke liye hum project ke root folder mein ek aur file banate hain, .gitignore. Is file ke andar, hum bas .env likh denge.
.gitignore file:
# Ignore environment variables file
.env
# Other things to ignore...
__pycache__/
*.pyc
venv/
Ab jab tum git add . aur git commit karoge, Git is .env file ko dekhega hi nahi. Yeh tumhare local machine pe hi rahegi. Problem solved.
Common Galti: Forgetting .gitignore
Yeh sab se aam ghalti hai. Aap ne .env file bana li, sab aala. Lekin usko .gitignore mein daalna bhool gaye. Next time aap ne git push kiya, aapki secret tijori poori dunya ke saamne khul gayi. Hamesha, HAMESHA .env file banatay hi foran usko .gitignore mein add karo. Rule #1.
Code Mein Secrets Ko Use Kaise Karein? python-dotenv
Ab sawaal yeh hai ke agar secrets file mein hain, tou hamara Python code unko parhega kaise? Is ke liye ek choti si, lekin powerful library hai: python-dotenv.
Pehle isko install karlo:
pip install python-dotenv
Ab dekho isko use karna kitna aasaan hai. Main wohi code likh raha hoon jo prompt mein tha, aur ab main usko line-by-line samjhaunga.
# main.py (or any other Python file)
import os
from dotenv import load_dotenv
# Yeh line jaadu hai. Yeh .env file ko dhoond ke uske saare variables
# environment mein load kar deti hai.
load_dotenv()
# --- Ab hum secrets ko safely access kar sakte hain ---
# 1. The Live Trading Gate (sab se important)
# Default value 'false' hai, taake ghalti se bhi live trading na ho.
# .lower() ensures ke 'True', 'true', 'TRUE' sab kaam karein.
LIVE_TRADING = os.environ.get('ORACLE_LIVE_TRADING', 'false').lower() == 'true'
# 2. Capital Allocation
# Default 30 USD. float() mein convert kar rahe hain for calculations.
CAPITAL = float(os.environ.get('ORACLE_CAPITAL', '30'))
# 3. API Key Access
# Default empty string ''. Is se hum check kar sakte hain ke key hai ya nahi.
GEMINI_KEY = os.environ.get('GEMINI_API_KEY', '')
# --- Let's check our configuration ---
print("--- Oracle Bot Configuration ---")
print(f'Trading Mode: {"LIVE" if LIVE_TRADING else "PAPER/SIMULATION"}')
print(f'Capital per trade: ${CAPITAL}')
if GEMINI_KEY:
# Sirf pehle 5 aur aakhri 5 characters dikhao, for security.
print(f'Gemini API Key: {"Configured (sk...{})".format(GEMINI_KEY[-5:])}')
else:
print('Gemini API Key: Not found in .env file!')
print("---------------------------------")
Code Breakdown:
-
import os:osmodule Python ka built-in module hai jo aapko Operating System ke saath interact karne deta hai. Environment variables OS level pe store hotay hain, isliye humein iski zaroorat hai. -
from dotenv import load_dotenv: Humpython-dotenvlibrary se sirfload_dotenvfunction import kar rahe hain. -
load_dotenv(): This is the magic. Jab yeh line chalti hai, library aapke current folder mein.envfile dhoondti hai, usko parhti hai, aur uske andar likhe saareKEY=VALUEpairs ko system ke environment variables mein load kar deti hai, for the duration of your script's execution. -
os.environ.get('KEY', 'default_value'): Yeh professional tareeqa hai environment variables ko access karne ka.os.environek dictionary ki tarah hai jis mein saare environment variables hotay hain.['KEY']se bhi access kar sakte hain, lekin agarKEYexist na karti ho tou program crash ho jayega..get('KEY', 'default_value')behtar hai. Yeh 'KEY' ko dhoondne ki koshish karta hai. Agar mil gayi, tou uski value return karta hai. Agar nahi mili, tou crash hone ke bajaye, yeh aapki di huidefault_valuereturn karta hai. This makes your code robust and predictable.
The Live Trading Gate: ORACLE_LIVE_TRADING
Yeh concept itna zaroori hai ke isko alag se samjhana banta hai. Jab aap bot develop kar rahe hotay ho, aap 99% time "paper trading" ya simulation mode mein kaam karte ho. Aap nahi chahte ke har choti si change test karne ke liye aapke asli paise lagein.
ORACLE_LIVE_TRADING flag hamara safety switch hai.
.env file mein:
ORACLE_LIVE_TRADING=false
Python code mein, secrets can be safely loaded and used without exposing them in the codebase.
📺 Recommended Videos & Resources
- python-dotenv Documentation — Complete guide to environment variables in Python
- Type: Official Documentation
- Link description: Learn about load_dotenv() and environment variable handling
- Git & .gitignore Best Practices — Securing your repository
- Type: Atlassian Tutorial
- Link description: Learn how to prevent sensitive files from being committed
- Managing Secrets in Python Applications — Best practices for sensitive data
- Type: YouTube
- Link description: Search "Python environment variables best practices"
- os.environ vs .env: Understanding Scope — Python os module documentation
- Type: Python Official Docs
- Link description: Learn about environment variables and the os module
- Cryptocurrency Private Keys — Security Essentials — Understanding wallet security
- Type: Wikipedia
- Link description: Learn why private keys must never be exposed or hardcoded
🎯 Mini-Challenge
5-Minute Practical Task: Create a .env file in a test project directory with 3 dummy API keys (GEMINI_API_KEY, POLYMARKET_PRIVATE_KEY, CAPITAL=100). Create a .gitignore file that excludes .env. Then write a Python script using python-dotenv to load and print (partially masked) these values. Verify that the script runs successfully.
🖼️ Visual Reference
📊 Secrets Management Flow (RIGHT vs WRONG)
┌─────────────────────────────────┐
│ WRONG: Hardcoded in Code │
│ │
│ api_key = "sk-12345..." ◄───── │ EXPOSED!
│ main.py (committed to GitHub) │
└─────────────────────────────────┘
┌─────────────────────────────────┐
│ RIGHT: Environment Variables │
│ │
│ .env (NOT committed) │
│ ├─ API_KEY=sk-12345... │
│ ├─ PRIVATE_KEY=0x... │
│ └─ CAPITAL=100 │
│ │ │
│ ▼ │
│ .gitignore │
│ └─ .env (ignored by git) │
│ │
│ main.py │
│ load_dotenv() │
│ api_key = os.environ.get(...) │
│ (SAFE!) │
└─────────────────────────────────┘
Lesson Summary
Quiz: Environment Variables — Secrets Ko Safe Rakhna
4 questions to test your understanding. Score 60% or higher to pass.