dream
96 строк · 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(
29format="%(asctime)s - %(pathname)s - %(lineno)d - %(levelname)s - %(message)s",
30level=logging.DEBUG,
31)
32logger = logging.getLogger(__name__)
33
34
35app = Flask(__name__)
36health = HealthCheck(app, "/healthcheck")
37logging.getLogger("werkzeug").setLevel("WARNING")
38
39
40def handler(requested_data, random_seed=None):
41st_time = time.time()
42ctxs = load_ctxs(requested_data)
43random_seed = requested_data.get("random_seed", random_seed) # for tests
44
45responses = []
46for ctx in ctxs:
47try:
48# for tests
49if random_seed:
50random.seed(int(random_seed))
51ctx = actor(ctx)
52responses.append(get_response(ctx, actor))
53except Exception as exc:
54sentry_sdk.capture_exception(exc)
55logger.exception(exc)
56responses.append(("", 1.0, {}, {}, {}))
57
58total_time = time.time() - st_time
59logger.info(f"{SERVICE_NAME} exec time = {total_time:.3f}s")
60return responses
61
62
63try:
64test_server.run_test(handler)
65logger.info("test query processed")
66except Exception as exc:
67sentry_sdk.capture_exception(exc)
68logger.exception(exc)
69raise exc
70
71logger.info(f"{SERVICE_NAME} is loaded and ready")
72
73# import pathlib
74# import json
75
76# for in_file in pathlib.Path("tests").glob("./*_in.json"):
77# logger.error(in_file)
78# test_in = json.load(in_file.open())
79# responses = handler(test_in, RANDOM_SEED)
80# out_file = str(in_file).replace("in.json", "out.json")
81# import common.test_utils as t_utils
82
83# t_utils.save_to_test(responses, out_file, indent=4) # TEST
84
85
86@app.route("/respond", methods=["POST"])
87def respond():
88# import common.test_utils as t_utils; t_utils.save_to_test(request.json,"tests/favs_in.json",indent=4) # TEST
89# responses = handler(request.json, RANDOM_SEED) # TEST
90# import common.test_utils as t_utils; t_utils.save_to_test(responses,"tests/favs_out.json",indent=4) # TEST
91responses = handler(request.json)
92return jsonify(responses)
93
94
95if __name__ == "__main__":
96app.run(debug=False, host="0.0.0.0", port=SERVICE_PORT)
97