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