forked from NathanMyers17/case-04
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
41 lines (35 loc) · 1.32 KB
/
app.py
File metadata and controls
41 lines (35 loc) · 1.32 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
from datetime import datetime, timezone
from flask import Flask, request, jsonify
from flask_cors import CORS
from pydantic import ValidationError
from models import SurveySubmission, StoredSurveyRecord
from storage import append_json_line
app = Flask(__name__)
# Allow cross-origin requests so the static HTML can POST from localhost or file://
CORS(app, resources={r"/v1/*": {"origins": "*"}})
@app.route("/ping", methods=["GET"])
def ping():
"""Simple health check endpoint."""
return jsonify({
"status": "ok",
"message": "API is alive",
"utc_time": datetime.now(timezone.utc).isoformat()
})
@app.post("/v1/survey")
def submit_survey():
payload = request.get_json(silent=True)
if payload is None:
return jsonify({"error": "invalid_json", "detail": "Body must be application/json"}), 400
try:
submission = SurveySubmission(**payload)
except ValidationError as ve:
return jsonify({"error": "validation_error", "detail": ve.errors()}), 422
record = StoredSurveyRecord(
**submission.dict(),
received_at=datetime.now(timezone.utc),
ip=request.headers.get("X-Forwarded-For", request.remote_addr or "")
)
append_json_line(record.dict())
return jsonify({"status": "ok"}), 201
if __name__ == "__main__":
app.run(port=5000, debug=True)