-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebug_env.py
More file actions
157 lines (128 loc) Β· 5.6 KB
/
debug_env.py
File metadata and controls
157 lines (128 loc) Β· 5.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#!/usr/bin/env python3
"""
Debug script to test environment variables and API functionality
"""
import os
import sys
import asyncio
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
def check_env_vars():
"""Check if environment variables are loaded correctly"""
print("π Checking Environment Variables...\n")
# Check for .env file
env_file_exists = os.path.exists('.env')
print(f"π .env file exists: {'β
Yes' if env_file_exists else 'β No'}")
if env_file_exists:
try:
with open('.env', 'r') as f:
lines = [line.strip() for line in f.readlines() if line.strip() and not line.startswith('#')]
print(f"π .env file has {len(lines)} non-comment lines")
except Exception as e:
print(f"β Error reading .env file: {e}")
# Check environment variables
env_vars = {
'ALPHA_VANTAGE_API_KEY': os.getenv('ALPHA_VANTAGE_API_KEY'),
'FRED_API_KEY': os.getenv('FRED_API_KEY'),
'BLS_API_KEY': os.getenv('BLS_API_KEY')
}
print("\nπ Environment Variables Status:")
for var_name, var_value in env_vars.items():
if var_value:
masked_value = var_value[:4] + "*" * (len(var_value) - 8) + var_value[-4:] if len(var_value) > 8 else "****"
print(f" {var_name}: β
Set ({masked_value})")
else:
print(f" {var_name}: β Not set")
return all(var_value for var_value in env_vars.values())
async def test_api_calls():
"""Test actual API calls to verify keys work"""
print("\nπ§ͺ Testing API Calls...\n")
# Add the api directory to the path
sys.path.append('api')
try:
# Test Alpha Vantage - Oil
print("π’οΈ Testing Alpha Vantage (Oil)...")
from items import fetch_oil_usd
oil_price = await fetch_oil_usd()
if oil_price != 75.0: # Not the fallback price
print(f" β
Success: ${oil_price:.2f} per barrel")
else:
print(f" β οΈ Using fallback price: ${oil_price:.2f} (API key might be invalid)")
# Test Alpha Vantage - Gold
print("π Testing Alpha Vantage (Gold)...")
from items import fetch_gold_usd
gold_price = await fetch_gold_usd()
if gold_price != 2000.0: # Not the fallback price
print(f" β
Success: ${gold_price:.2f} per ounce")
else:
print(f" β οΈ Using fallback price: ${gold_price:.2f} (API key might be invalid)")
# Test FRED - Bread
print("π Testing FRED API (Bread)...")
from items import fetch_bread_usd
bread_price = await fetch_bread_usd()
if bread_price != 2.50: # Not the fallback price
print(f" β
Success: ${bread_price:.2f} per loaf")
else:
print(f" β οΈ Using fallback price: ${bread_price:.2f} (API key might be invalid)")
except Exception as e:
print(f"β Error testing APIs: {e}")
return False
return True
async def test_conversion():
"""Test the conversion functionality"""
print("\nπ± Testing Conversion API...\n")
try:
from index import convert
# Test conversion with oil
result = await convert(btc_amount=0.1, item='oil', direction='btc_to_item')
print(f"π° Conversion Test: 0.1 BTC = {result.quantity:.2f} barrels of oil")
print(f" Oil price: ${result.usd_item:.2f}")
print(f" BTC price: ${result.btc_price:.2f}")
print(f" Total value: ${result.usd_total:.2f}")
return True
except Exception as e:
print(f"β Error testing conversion: {e}")
return False
def show_setup_instructions():
"""Show instructions for setting up API keys"""
print("\nπ Setup Instructions:")
print("\n1. Edit the .env file in this directory:")
print(" nano .env")
print("\n2. Replace the placeholder values with your actual API keys:")
print(" ALPHA_VANTAGE_API_KEY=your_actual_alpha_vantage_key")
print(" FRED_API_KEY=your_actual_fred_key")
print(" BLS_API_KEY=your_actual_bls_key")
print("\n3. Save the file and run this debug script again")
print("\nπ Get your API keys:")
print(" β’ Alpha Vantage: https://www.alphavantage.co/support/#api-key")
print(" β’ FRED: https://api.stlouisfed.org/")
print(" β’ BLS: https://www.bls.gov/developers/")
async def main():
"""Main debug function"""
print("π BTC Real-World Converter - Environment Debug Tool\n")
# Check environment variables
env_ok = check_env_vars()
if not env_ok:
print("\nβ Some environment variables are missing!")
show_setup_instructions()
return 1
# Test API calls
api_ok = await test_api_calls()
# Test conversion
conversion_ok = await test_conversion()
# Summary
print(f"\nπ Debug Summary:")
print(f" Environment Variables: {'β
' if env_ok else 'β'}")
print(f" API Calls: {'β
' if api_ok else 'β'}")
print(f" Conversion: {'β
' if conversion_ok else 'β'}")
if env_ok and api_ok and conversion_ok:
print("\nπ Everything looks good! Your API keys are working correctly.")
print(" You can now run the app with: uvicorn api.index:app --reload")
else:
print("\nβ Some issues found. Check the output above and fix them.")
if not env_ok:
show_setup_instructions()
return 0 if (env_ok and api_ok and conversion_ok) else 1
if __name__ == "__main__":
exit_code = asyncio.run(main())