-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.py
More file actions
74 lines (58 loc) · 1.9 KB
/
config.py
File metadata and controls
74 lines (58 loc) · 1.9 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
"""
Configuration management for Redfin Scraper API.
Handles API key storage and retrieval.
"""
import os
import json
CONFIG_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "config.json")
BASE_URL = "https://redfin.realtyapi.io"
HEADER_KEY = "x-realtyapi-key"
def load_api_key():
"""Load API key from config.json or environment variable."""
# 1. Check environment variable
env_key = os.environ.get("REALTYAPI_KEY")
if env_key:
return env_key
# 2. Check config.json
if os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE, "r") as f:
data = json.load(f)
key = data.get("api_key", "").strip()
if key:
return key
return None
def save_api_key(api_key):
"""Save API key to config.json."""
data = {}
if os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE, "r") as f:
data = json.load(f)
data["api_key"] = api_key
with open(CONFIG_FILE, "w") as f:
json.dump(data, f, indent=2)
print("API key saved to config.json")
def get_headers(api_key=None):
"""Return request headers with the API key."""
key = api_key or load_api_key()
if not key:
return None
return {HEADER_KEY: key}
def ensure_api_key():
"""Ensure an API key is available, prompt user if not."""
key = load_api_key()
if key:
return key
print("\n" + "=" * 60)
print(" RealtyAPI Key Required")
print("=" * 60)
print("\nNo API key found. Get your key at: https://www.realtyapi.io")
print("\nYou can also set it via environment variable:")
print(" export REALTYAPI_KEY=rt_your_key_here\n")
key = input("Enter your RealtyAPI key: ").strip()
if not key:
print("No key provided. Exiting.")
return None
save = input("Save key for future use? (y/n): ").strip().lower()
if save == "y":
save_api_key(key)
return key