dream

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

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

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

13

14
from common.dff.integration.actor import load_ctxs, get_response
15

16
from scenario.main import actor
17

18
import test_server
19

20

21
ignore_logger("root")
22

23
sentry_sdk.init(os.getenv("SENTRY_DSN"))
24
SERVICE_NAME = os.getenv("SERVICE_NAME")
25
SERVICE_PORT = int(os.getenv("SERVICE_PORT"))
26
RANDOM_SEED = int(os.getenv("RANDOM_SEED", 2718))
27

28
logging.basicConfig(
29
    format="%(asctime)s - %(pathname)s - %(lineno)d - %(levelname)s - %(message)s",
30
    level=logging.DEBUG,
31
)
32
logger = logging.getLogger(__name__)
33

34

35
app = Flask(__name__)
36
health = HealthCheck(app, "/healthcheck")
37
logging.getLogger("werkzeug").setLevel("WARNING")
38

39

40
def handler(requested_data, random_seed=None):
41
    st_time = time.time()
42
    ctxs = load_ctxs(requested_data)
43
    random_seed = requested_data.get("random_seed", random_seed)  # for tests
44

45
    responses = []
46
    for ctx in ctxs:
47
        try:
48
            # for tests
49
            if random_seed:
50
                random.seed(int(random_seed))
51
            ctx = actor(ctx)
52
            responses.append(get_response(ctx, actor))
53
        except Exception as exc:
54
            sentry_sdk.capture_exception(exc)
55
            logger.exception(exc)
56
            responses.append(("", 1.0, {}, {}, {}))
57

58
    total_time = time.time() - st_time
59
    logger.info(f"{SERVICE_NAME} exec time = {total_time:.3f}s")
60
    return responses
61

62

63
try:
64
    test_server.run_test(handler)
65
    logger.info("test query processed")
66
except Exception as exc:
67
    sentry_sdk.capture_exception(exc)
68
    logger.exception(exc)
69
    raise exc
70

71
logger.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"])
87
def 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
91
    responses = handler(request.json)
92
    return jsonify(responses)
93

94

95
if __name__ == "__main__":
96
    app.run(debug=False, host="0.0.0.0", port=SERVICE_PORT)
97

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

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

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

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