-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
184 lines (159 loc) · 5.57 KB
/
Copy pathserver.py
File metadata and controls
184 lines (159 loc) · 5.57 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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
#!/usr/bin/env python3
"""
SheetDB REST API Server - Entry point script.
This script starts the FastAPI server with configuration from environment
variables or command-line arguments.
"""
import os
import sys
import argparse
import logging
from pathlib import Path
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger("sheetdb.server")
def main():
"""Main entry point for the server."""
parser = argparse.ArgumentParser(
description="SheetDB REST API Server - Google Sheets as a relational database"
)
# Server configuration
parser.add_argument(
'--host',
default=os.getenv('SHEETDB_HOST', '0.0.0.0'),
help='Host to bind to (default: 0.0.0.0)'
)
parser.add_argument(
'--port',
type=int,
default=int(os.getenv('SHEETDB_PORT', '8000')),
help='Port to bind to (default: 8000)'
)
# SheetDB configuration
parser.add_argument(
'--credentials',
default=os.getenv('GOOGLE_CREDENTIALS'),
help='Path to Google service account credentials JSON file'
)
parser.add_argument(
'--spreadsheet-id',
default=os.getenv('SPREADSHEET_ID'),
help='Google Spreadsheet ID'
)
parser.add_argument(
'--sheet-url',
default=os.getenv('SHEET_URL'),
help='Public sheet URL (for public mode)'
)
parser.add_argument(
'--schema',
default=os.getenv('SCHEMA_PATH', 'schema.yaml'),
help='Path to schema YAML file (default: schema.yaml)'
)
parser.add_argument(
'--cache-mode',
choices=['aggressive', 'smart', 'lazy', 'none'],
default=os.getenv('CACHE_MODE', 'aggressive'),
help='Cache mode (default: aggressive)'
)
parser.add_argument(
'--cache-ttl',
type=int,
default=int(os.getenv('CACHE_TTL', '300')),
help='Cache TTL in seconds for smart mode (default: 300)'
)
parser.add_argument(
'--mode',
choices=['public', 'authenticated', 'hybrid'],
default=os.getenv('SHEETDB_MODE'),
help='Operating mode (auto-detected if not specified)'
)
# CORS configuration
parser.add_argument(
'--cors-origins',
default=os.getenv('CORS_ORIGINS', '*'),
help='Comma-separated list of allowed CORS origins (default: *)'
)
# Authentication
parser.add_argument(
'--api-keys',
default=os.getenv('API_KEYS'),
help='Comma-separated list of valid API keys (optional)'
)
# Development options
parser.add_argument(
'--reload',
action='store_true',
help='Enable auto-reload for development'
)
parser.add_argument(
'--log-level',
choices=['DEBUG', 'INFO', 'WARNING', 'ERROR'],
default=os.getenv('LOG_LEVEL', 'INFO'),
help='Logging level (default: INFO)'
)
args = parser.parse_args()
# Set logging level
logging.getLogger().setLevel(getattr(logging, args.log_level))
# Validate configuration
if not args.sheet_url and (not args.credentials or not args.spreadsheet_id):
logger.error(
"Must provide either --sheet-url for public mode, or "
"--credentials and --spreadsheet-id for authenticated mode"
)
sys.exit(1)
# Check if schema file exists
if args.schema and not Path(args.schema).exists():
logger.warning(f"Schema file not found: {args.schema}")
logger.info("Server will start but may fail if schema is required")
# Parse CORS origins
cors_origins = [origin.strip() for origin in args.cors_origins.split(',')]
# Parse API keys
api_keys = None
if args.api_keys:
api_keys = [key.strip() for key in args.api_keys.split(',')]
logger.info(f"API key authentication enabled with {len(api_keys)} key(s)")
else:
logger.warning("No API keys configured - authentication disabled")
# Add parent directory to path if running from sheetdb_server directory
if os.path.basename(os.getcwd()) == 'sheetdb_server':
sys.path.insert(0, os.path.dirname(os.getcwd()))
# Import here to avoid circular imports
from sheetdb_server.app import create_app
import uvicorn
# Create app
logger.info("Creating SheetDB REST API server...")
logger.info(f"Mode: {args.mode or 'auto-detect'}")
logger.info(f"Cache mode: {args.cache_mode}")
logger.info(f"Schema: {args.schema}")
try:
app = create_app(
credentials=args.credentials,
spreadsheet_id=args.spreadsheet_id,
sheet_url=args.sheet_url,
schema_path=args.schema if Path(args.schema).exists() else None,
cache_mode=args.cache_mode,
cache_ttl=args.cache_ttl if args.cache_mode == 'smart' else None,
mode=args.mode,
allowed_origins=cors_origins,
api_keys=api_keys
)
logger.info(f"Starting server on {args.host}:{args.port}")
logger.info(f"API documentation: http://{args.host}:{args.port}/docs")
logger.info(f"Health check: http://{args.host}:{args.port}/health")
# Run server
uvicorn.run(
app,
host=args.host,
port=args.port,
reload=args.reload,
log_level=args.log_level.lower()
)
except Exception as e:
logger.error(f"Failed to start server: {e}")
sys.exit(1)
if __name__ == "__main__":
main()