dream
91 строка · 2.6 Кб
1#!/usr/bin/env python
2
3import logging
4import time
5import os
6import random
7
8import sentry_sdk
9from flask import Flask, request, jsonify
10from healthcheck import HealthCheck
11from sentry_sdk.integrations.logging import ignore_logger
12
13import test_server
14from common.dff.integration.actor import load_ctxs, get_response
15from scenario.main import actor
16
17
18ignore_logger("root")
19
20sentry_sdk.init(os.getenv("SENTRY_DSN"))
21SERVICE_NAME = os.getenv("SERVICE_NAME")
22SERVICE_PORT = int(os.getenv("SERVICE_PORT"))
23RANDOM_SEED = int(os.getenv("RANDOM_SEED", 2718))
24
25logging.basicConfig(format="%(asctime)s - %(pathname)s - %(lineno)d - %(levelname)s - %(message)s", level=logging.INFO)
26logger = logging.getLogger(__name__)
27
28
29app = Flask(__name__)
30health = HealthCheck(app, "/healthcheck")
31logging.getLogger("werkzeug").setLevel("WARNING")
32
33
34def handler(requested_data, random_seed=None):
35st_time = time.time()
36ctxs = load_ctxs(requested_data)
37random_seed = requested_data.get("random_seed", random_seed) # for tests
38
39responses = []
40for ctx in ctxs:
41try:
42# for tests
43if random_seed:
44random.seed(int(random_seed))
45ctx = actor(ctx)
46responses.append(get_response(ctx, actor))
47except Exception as exc:
48sentry_sdk.capture_exception(exc)
49logger.exception(exc)
50responses.append(("", 0.0, {}, {}, {}))
51
52total_time = time.time() - st_time
53logger.info(f"{SERVICE_NAME} exec time = {total_time:.3f}s")
54return responses
55
56
57try:
58test_server.run_test(handler)
59logger.info("test query processed")
60except Exception as exc:
61sentry_sdk.capture_exception(exc)
62logger.exception(exc)
63raise exc
64
65logger.info(f"{SERVICE_NAME} is loaded and ready")
66
67
68# import pathlib
69# import json
70
71# for in_file in pathlib.Path("tests").glob("./*_in.json"):
72# logger.error(in_file)
73# test_in = json.load(in_file.open())
74# responses = handler(test_in, RANDOM_SEED)
75# out_file = str(in_file).replace("in.json", "out.json")
76# import common.test_utils as t_utils
77
78# t_utils.save_to_test(responses, out_file, indent=4) # TEST
79
80
81@app.route("/respond", methods=["POST"])
82def respond():
83# import common.test_utils as t_utils; t_utils.save_to_test(request.json,"tests/test_in.json",indent=4) # TEST
84# responses = handler(request.json, RANDOM_SEED) # TEST
85# import common.test_utils as t_utils; t_utils.save_to_test(responses,"tests/test_out.json",indent=4) # TEST
86responses = handler(request.json)
87return jsonify(responses)
88
89
90if __name__ == "__main__":
91app.run(debug=False, host="0.0.0.0", port=SERVICE_PORT)
92