dream

Форк
0
94 строки · 2.7 Кб
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
from common.dff.integration.actor import load_ctxs, get_response
14

15
from scenario.main import actor
16
import test_server
17

18

19
ignore_logger("root")
20

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

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

30

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

35

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

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

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

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

72
try:
73
    test_server.run_test(handler)
74
    logger.info("test query processed")
75
except Exception as exc:
76
    sentry_sdk.capture_exception(exc)
77
    logger.exception(exc)
78
    raise exc
79

80
logger.info(f"{SERVICE_NAME} is loaded and ready")
81

82

83
@app.route("/respond", methods=["POST"])
84
def respond():
85
    # test
86
    # 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)  # TEST
88
    # import common.test_utils as t_utils; t_utils.save_to_test(responses,"tests/tell_funny_story_out.json",indent=4)
89
    responses = handler(request.json)
90
    return jsonify(responses)
91

92

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

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

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

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

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