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