diff --git a/server.py b/server.py index 3aa993e..472c09c 100644 --- a/server.py +++ b/server.py @@ -1,21 +1,48 @@ +"""Сервер-пустышка, для генерации ответов. +Можно проверить, что он возвращает, сделав запрос: + +httpie +http get 127.0.0.1:5000/api/portal/get columns:='["hostname"]' limit=9 + +curl (надо быть в папке проекта, request.json лежит в ней) +curl --request GET \ +--header "Content-Type: application/json" \ +--data @request.json \ +127.0.0.1:5000/api/portal/get + +""" + from flask import Flask, jsonify, request import json +import secrets app = Flask(__name__) -# http get 127.0.0.1:5000/api/portal/get columns:='["hostname"]' limit=9 + @app.route("/api/portal/get", methods=["GET"]) def index(): - print(request.json) + """ + Единственная функция сервера-пирожочка. + + Вернет json, в формате: + {"result": [ + {"hostname": "content-creator-random_hex[8]"}, + ... + ], + "done": true} + + В этой реализации, принимает аргумент `limit=N`, N -- количество + генерируемых значений, а не выборка. + """ + # print(request) columns = request.json.get("columns") limit = int(request.json.get("limit")) hosts: List[dict] = [] - for host in range(1, limit + 1): - hosts.append({"hostname": f"content-creator-{host}"}) + for host in range(0, limit): + hosts.append({"hostname": f"content-creator-{secrets.token_hex(4)}"}) - # определить количество хостов в запросе ключ `limit` return jsonify({"result": hosts, "done": True}) diff --git a/solution.py b/solution.py index da79ae9..aab24f1 100644 --- a/solution.py +++ b/solution.py @@ -3,9 +3,10 @@ import requests import json from typing import List import os +import configparser -def write_config_file( +async def write_config_file( server_name: str, path_to_template_file: str, path_for_config: str ) -> None: template: str = "" @@ -23,12 +24,20 @@ def write_config_file( file.write(config_body) -def send_request(server: str, columns: list, limit: int) -> dict: +async def send_request(server: str, columns: list, limit: int = 1) -> dict: response = requests.get(server, json={"columns": columns, "limit": limit}) + return response.json() -def get_hosts(server_response: dict) -> List[str]: +async def get_hosts(server_response: dict) -> List[str]: + """Получить хосты из ответа сервера. + + Parameters + ---------- + server_response : dict + """ + hosts: list = [] for host in server_response.get("result"): @@ -37,24 +46,58 @@ def get_hosts(server_response: dict) -> List[str]: return hosts -def main(): - TEMPLATE = "template_conf.conf" - PATH_FOR_CONFIG = "ng" - FREQUENCY_SEC = 10 +async def read_config(path_to_conf_file: str, section: str = "Main") -> dict: + """ + Считать конфиг с помощью `configparser`. + + Parameters + ---------- + path_to_conf_file: str + Путь к файлу конфига. Можно указывать относительный. + + section: str + Секция в конфиге, которую нужно считывать. По-умолчанию секция [Main]. + + Raises + ------ + KeyError + Если в конфиге не найдено указанной секции. + + Returns + ------- + dict + Словарь, из значений указанной секции. + """ + config = configparser.ConfigParser() + config.read(os.path.abspath(path_to_conf_file)) - resp = send_request( - "http://127.0.0.1:5000/api/portal/get", columns=["hostname"], limit=9 - ) + if section not in config.sections(): + raise KeyError(f"Section {section} not found in config file!") - hosts = get_hosts(resp) + return dict(config.items(section)) - for host in hosts: - write_config_file( - server_name=host, - path_to_template_file=TEMPLATE, - path_for_config=PATH_FOR_CONFIG, + +async def main(): + + cnf = await read_config("service.conf") + + wait_sec: int = int(cnf["frequency_sec"]) + + while True: + resp = await send_request( + cnf["central_host_url"], columns=["hostname"], limit=9 ) + hosts = await get_hosts(resp) + + for host in hosts: + await write_config_file( + server_name=host, + path_to_template_file=cnf["template"], + path_for_config=cnf["path_for_config"], + ) + await asyncio.sleep(wait_sec) + if __name__ == "__main__": - main() + asyncio.run(main())