dream

Форк
0
91 строка · 2.6 Кб
1
#!/usr/bin/env python
2

3
import logging
4
import time
5
import os
6
import random
7

8
import sentry_sdk
9
from flask import Flask, request, jsonify
10
from healthcheck import HealthCheck
11
from sentry_sdk.integrations.logging import ignore_logger
12

13
import test_server
14
from common.dff.integration.actor import load_ctxs, get_response
15
from scenario.main import actor
16

17

18
ignore_logger("root")
19

20
sentry_sdk.init(os.getenv("SENTRY_DSN"))
21
SERVICE_NAME = os.getenv("SERVICE_NAME")
22
SERVICE_PORT = int(os.getenv("SERVICE_PORT"))
23
RANDOM_SEED = int(os.getenv("RANDOM_SEED", 2718))
24

25
logging.basicConfig(format="%(asctime)s - %(pathname)s - %(lineno)d - %(levelname)s - %(message)s", level=logging.INFO)
26
logger = logging.getLogger(__name__)
27

28

29
app = Flask(__name__)
30
health = HealthCheck(app, "/healthcheck")
31
logging.getLogger("werkzeug").setLevel("WARNING")
32

33

34
def handler(requested_data, random_seed=None):
35
    st_time = time.time()
36
    ctxs = load_ctxs(requested_data)
37
    random_seed = requested_data.get("random_seed", random_seed)  # for tests
38

39
    responses = []
40
    for ctx in ctxs:
41
        try:
42
            # for tests
43
            if random_seed:
44
                random.seed(int(random_seed))
45
            ctx = actor(ctx)
46
            responses.append(get_response(ctx, actor))
47
        except Exception as exc:
48
            sentry_sdk.capture_exception(exc)
49
            logger.exception(exc)
50
            responses.append(("", 0.0, {}, {}, {}))
51

52
    total_time = time.time() - st_time
53
    logger.info(f"{SERVICE_NAME} exec time = {total_time:.3f}s")
54
    return responses
55

56

57
try:
58
    test_server.run_test(handler)
59
    logger.info("test query processed")
60
except Exception as exc:
61
    sentry_sdk.capture_exception(exc)
62
    logger.exception(exc)
63
    raise exc
64

65
logger.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"])
82
def 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
86
    responses = handler(request.json)
87
    return jsonify(responses)
88

89

90
if __name__ == "__main__":
91
    app.run(debug=False, host="0.0.0.0", port=SERVICE_PORT)
92

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.