-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocal-test-server.py
More file actions
executable file
·165 lines (131 loc) · 5.62 KB
/
Copy pathlocal-test-server.py
File metadata and controls
executable file
·165 lines (131 loc) · 5.62 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
#!/usr/bin/env python3
"""
BeanRatio Local Test Server
Lambda関数をローカルでテストするためのシンプルなHTTPサーバー
"""
import sys
import json
import os
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs, unquote
# Lambda関数をインポート
sys.path.insert(0, '/home/ec2-user/BeanRatio/lambda')
os.environ['S3_BUCKET_NAME'] = 'beanratio-data'
os.environ['AUTH_TOKEN'] = 'test-token-12345'
os.environ['WEB_DIR'] = '/home/ec2-user/BeanRatio/web'
os.environ['FUNCTION_URL'] = 'http://localhost:3000'
# LocalStack S3エンドポイント設定
os.environ['AWS_ENDPOINT_URL_S3'] = 'http://localhost:4566'
os.environ['AWS_ACCESS_KEY_ID'] = 'test'
os.environ['AWS_SECRET_ACCESS_KEY'] = 'test'
os.environ['AWS_DEFAULT_REGION'] = 'ap-northeast-1'
print(f"DEBUG: AUTH_TOKEN環境変数 = {os.environ.get('AUTH_TOKEN')}")
from functions.api_handler import lambda_handler
class LambdaHTTPHandler(BaseHTTPRequestHandler):
"""Lambda関数をHTTPハンドラーでラップ"""
def do_GET(self):
self.handle_request()
def do_POST(self):
self.handle_request()
def do_PUT(self):
self.handle_request()
def do_DELETE(self):
self.handle_request()
def do_OPTIONS(self):
self.send_response(200)
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
self.send_header('Access-Control-Allow-Headers', 'Content-Type')
self.end_headers()
def handle_request(self):
"""HTTPリクエストをLambda形式に変換して実行"""
try:
# URLをパース
parsed_url = urlparse(self.path)
path = parsed_url.path
query_string = parsed_url.query
query_params = parse_qs(query_string)
# クエリパラメータを単一値に変換
query_string_parameters = {k: v[0] for k, v in query_params.items()}
# ボディを読み込み
body = None
if self.command in ['POST', 'PUT']:
content_length = int(self.headers.get('Content-Length', 0))
if content_length > 0:
body = self.rfile.read(content_length).decode('utf-8')
# Lambda Event形式に変換
event = {
'requestContext': {
'http': {
'method': self.command,
'path': path,
'sourceIp': self.client_address[0]
}
},
'rawPath': path,
'body': body,
'queryStringParameters': query_string_parameters if query_string_parameters else None,
'headers': dict(self.headers)
}
print(f"\n{'='*60}")
print(f"REQUEST: {self.command} {path}")
print(f"Query: {query_string_parameters}")
if body:
print(f"Body: {body[:200]}")
print(f"{'='*60}")
# Lambda関数を実行
response = lambda_handler(event, None)
# レスポンスを送信
status_code = response.get('statusCode', 200)
response_headers = response.get('headers', {})
response_body = response.get('body', '{}')
self.send_response(status_code)
# Lambda関数からのヘッダーを優先して設定
content_type = response_headers.get('Content-Type', 'application/json')
self.send_header('Content-Type', content_type)
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
self.send_header('Access-Control-Allow-Headers', 'Content-Type')
for header, value in response_headers.items():
if header.lower() not in ['content-type', 'access-control-allow-origin', 'access-control-allow-methods', 'access-control-allow-headers']:
self.send_header(header, value)
self.end_headers()
self.wfile.write(response_body.encode('utf-8'))
print(f"RESPONSE: {status_code}")
print(f"Body: {response_body[:200]}")
except Exception as e:
print(f"ERROR: {e}")
import traceback
traceback.print_exc()
self.send_response(500)
self.send_header('Content-Type', 'application/json')
self.end_headers()
error_response = json.dumps({'error': str(e)})
self.wfile.write(error_response.encode('utf-8'))
def log_message(self, format, *args):
"""ログ出力を制御"""
# BaseHTTPRequestHandlerのログは出力しない(自前でやる)
pass
def main():
"""HTTPサーバーを起動"""
host = 'localhost'
port = 3000
server = HTTPServer((host, port), LambdaHTTPHandler)
print(f"\n{'='*60}")
print(f"BeanRatio Local Test Server")
print(f"{'='*60}")
print(f"Server running at: http://{host}:{port}")
print(f"Token: test-token-12345")
print(f"\nExample requests:")
print(f" GET http://{host}:{port}/beans?token=test-token-12345")
print(f" POST http://{host}:{port}/beans?token=test-token-12345")
print(f" Body: {{'name':'Test Bean','notes':'Test notes'}}")
print(f"\nPress Ctrl+C to stop")
print(f"{'='*60}\n")
try:
server.serve_forever()
except KeyboardInterrupt:
print("\n\nServer stopped.")
server.server_close()
if __name__ == '__main__':
main()