From 0832fc9326f67651672d3b34bc723c5ae585ea55 Mon Sep 17 00:00:00 2001 From: Wiltort Date: Fri, 21 Jun 2024 21:14:57 +0500 Subject: [PATCH 1/2] =?UTF-8?q?=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=B0=D0=B5?= =?UTF-8?q?=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .flaskenv | 2 + .gitignore | 160 +++++++++++++++++++++++++++ app.db | Bin 0 -> 40960 bytes app/__init__.py | 23 ++++ app/api/__init__.py | 5 + app/api/errors.py | 15 +++ app/api/services.py | 80 ++++++++++++++ app/models.py | 119 ++++++++++++++++++++ config.py | 13 +++ migrations/README | 1 + migrations/alembic.ini | 50 +++++++++ migrations/env.py | 113 +++++++++++++++++++ migrations/script.py.mako | 24 ++++ migrations/versions/c1ef43f24351_.py | 56 ++++++++++ task_python.py | 4 + 15 files changed, 665 insertions(+) create mode 100644 .flaskenv create mode 100644 .gitignore create mode 100644 app.db create mode 100644 app/__init__.py create mode 100644 app/api/__init__.py create mode 100644 app/api/errors.py create mode 100644 app/api/services.py create mode 100644 app/models.py create mode 100644 config.py create mode 100644 migrations/README create mode 100644 migrations/alembic.ini create mode 100644 migrations/env.py create mode 100644 migrations/script.py.mako create mode 100644 migrations/versions/c1ef43f24351_.py create mode 100644 task_python.py diff --git a/.flaskenv b/.flaskenv new file mode 100644 index 0000000..76d1782 --- /dev/null +++ b/.flaskenv @@ -0,0 +1,2 @@ +FLASK_APP=task_python.py +SECRET_KEY=slks;qwepoir diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..68bc17f --- /dev/null +++ b/.gitignore @@ -0,0 +1,160 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ diff --git a/app.db b/app.db new file mode 100644 index 0000000000000000000000000000000000000000..a4d50e70234796b7f03d77a13180b5959ac4b156 GIT binary patch literal 40960 zcmeI)Z%^7l9Ki8b9SEqH>;WTY$;HG3!m>;qCO$A3)9Q#=XT?pQtSQiCje-t}^T{6I z-pbyD?`jWyxGOC}iH>9smSMgP2mNz*+y|54m3c)~l{Z2t ziV_b}ME*|5l#ppkrrx6VR{roCS6()5W@mpY(V2vjoK4=$+{~QLB<7lP>BMeg_YWmG zga85vAbY+`i0rDo0m@Y-hJ^+Lo1Xu zQ7*hKY2v<8A`_1}HBr>d+Ky%jeZMU9qf+UGh{qaM-4-7T#^$?%ky(444IQl6t!mS` zaGmppC~L>E)IiDiMscrToQPfRL}Z*=HlF=79ZBWW>UXD6v#*>hv*lWDyJfa7YL;u) zOw09m#Dew~^)2mK+?P-6>%z|~GX2uoQZ$mvrd4~Wey;v%`R`z1Hy>Dp69o>`9 z^owVOp>1o1rf+J8BG?@SCV8v0a|`OXJGfvlb>;l^NYLdYy?Ah>$)VDV%|O;}Sp02~ z=^7?))%o=WwexhiW;t>`#v`c_e>(M7f7*E_r^&*CdL8ux=eH>6ad', methods=['GET']) +def get_statuses(id): + ''' + По имени сервиса выдает историю изменения + состояния и все данные по каждому состоянию + ''' + return jsonify(Service.query.get_or_404(id).statuses_to_dict()) + + +@bp.route('/services', methods=['GET']) +def get_services(): + ''' + Выводит список сервисов с актуальным состоянием + ''' + return jsonify(Service.all_services()) + + +@bp.route('/services//sla', methods=['GET']) +def get_sla(id): + ''' + По указанному интервалу выдается информация + о том сколько не работал сервис и считать SLA + в процентах до 3-й запятой + ''' + from_str = request.args.get('from_dt', type=str) + to_str = request.args.get('to_dt', type=str) + service = Service.query.get_or_404(id) + try: + from_dt = dt.datetime.strptime(from_str, '%Y-%m-%d %H:%M:%S') + to_dt = dt.datetime.strptime(to_str, '%Y-%m-%d %H:%M:%S') + except Exception: + return bad_request('use ISO 8601 for datetime objects: "%Y-%m-%d %H:%M:%S"') + return jsonify(service.get_sla(from_dt=from_dt, to_dt=to_dt)) + +@bp.route('/services', methods=['POST']) +def create_service(): + ''' + Получает и сохраняет данные: имя, состояние, описание + ''' + data = request.get_json() or {} + if 'name' not in data or 'status' not in data or 'description' not in data: + return bad_request('must include name, status and description') + if Service.query.filter_by(name=data['name']).first(): + return bad_request('please use a different name') + if data['status'] not in ['out of service', 'online', 'unstable']: + return bad_request('status must be one of "out of service", "online", "unstable"') + service = Service() + service.from_dict(data=data, new_service=True) + db.session.add(service) + db.session.commit() + response = jsonify(service.actual_status()) + response.status_code = 201 + return response + + +@bp.route('/services/', methods=['PUT']) +def update_service(id): + ''' + обновление статуса + ''' + service = Service.query.get_or_404(id) + data = request.get_json() or {} + if 'name' in data and data['name'] != service.name and \ + Service.query.filter_by(name=data['name']).first(): + return bad_request('please use a different name') + if 'status' in data and data['status'] == service.statuses[-1].name: + return bad_request('status is not changed') + if 'status' in data and data['status'] not in ['out of service', 'online', 'unstable']: + return bad_request('status must be one of "out of service", "online", "unstable"') + service.from_dict(data, new_service=False) + db.session.commit() + return jsonify(service.actual_status()) diff --git a/app/models.py b/app/models.py new file mode 100644 index 0000000..5c8c08d --- /dev/null +++ b/app/models.py @@ -0,0 +1,119 @@ +from typing import List +from datetime import datetime, timezone, timedelta +from sqlalchemy import ForeignKey, String, Text, select +from sqlalchemy.orm import Mapped, mapped_column, relationship +from app import db + + +class Service(db.Model): + __tablename__ = 'service' + + id: Mapped[int] = mapped_column(primary_key=True) + name: Mapped[str] = mapped_column( + String(64), index=True, unique=True) + description: Mapped[str] = mapped_column(Text) + + statuses: Mapped[List["Status"]] = relationship( + back_populates="service", cascade="all, delete-orphan" + ) + + def __repr__(self): + return ''.format(self.name) + + def actual_status(self): + data = { + 'name': self.name, + 'status': self.statuses[-1].name, + 'description': self.description} + return data + + def from_dict(self, data, new_service=False): + for field in ['name', 'description']: + if field in data: + setattr(self, field, data[field]) + if new_service: + if 'status' in data: + s = Status(name=data['status']) + self.statuses.append(s) + else: + if 'status' in data: + name = data['status'] + if name != self.statuses[-1].name: + s = Status(name=data['status']) + self.statuses.append(s) + + @staticmethod + def all_services(): + services = Service.query.all() + data = { + 'items': [item.actual_status() for item in services] + } + return data + + def statuses_to_dict(self): + data = [item.to_dict() for item in self.statuses] + return data + + def get_sla(self, from_dt, to_dt): + statuses_list = self.statuses + history = [] + total_time = to_dt - from_dt + not_working_time = timedelta(seconds=0) + data = {'not_working_time': f'{not_working_time.total_seconds()} s', 'sla': '0.000 %'} + left = {} + for i, st in enumerate(statuses_list): + if st.updated_at <= from_dt: + left = {'index': i, 'status': st.name, 'dt': st.updated_at} + if st.updated_at > from_dt and st.updated_at < to_dt: + history.append( + {'index': i, 'status': st.name, 'dt': st.updated_at}) + if st.updated_at >= to_dt: + break + if not history: + if left != {}: + if left['status'] == 'out of service': + data['not_working_time'] = f'{total_time.total_seconds()} s' + return data + data['sla'] = '100.000 %' + return data + data['not_working_time'] = f'{total_time.total_seconds()} s' + return data + + if left != {}: + current_status = left + else: + current_status = {'index': None, + 'status': 'out of service', 'dt': from_dt} + for item in history: + if current_status['status'] == 'out of service': + not_working_time += item['dt'] - current_status['dt'] + current_status = item + if current_status['status'] == 'out of service': + not_working_time += to_dt - current_status['dt'] + sla = "{:.3f}".format((total_time.total_seconds( + )-not_working_time.total_seconds())/total_time.total_seconds()*100)+" %" + data['sla'] = sla + data['not_working_time'] = f'{not_working_time.total_seconds()} s' + return data + + +class Status(db.Model): + __tablename__ = "status" + + id: Mapped[int] = mapped_column(primary_key=True) + updated_at: Mapped[datetime] = mapped_column( + index=True, default=lambda: datetime.now(timezone.utc)) + name: Mapped[str] = mapped_column(String(32), index=True) + service_id: Mapped[int] = mapped_column(ForeignKey("service.id")) + + service: Mapped[Service] = relationship(back_populates='statuses') + + def to_dict(self): + data = { + 'name': self.name, + 'updated_at': self.updated_at.isoformat()+'Z' + } + return data + + def __repr__(self): + return ''.format(self.name) diff --git a/config.py b/config.py new file mode 100644 index 0000000..ce99357 --- /dev/null +++ b/config.py @@ -0,0 +1,13 @@ +import os +from dotenv import load_dotenv +load_dotenv() + +basedir = os.path.abspath(os.path.dirname(__file__)) + + +class Config(object): + DEBUG = True + SECRET_KEY = os.environ.get('SECRET_KEY') or '123456' + SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \ + 'mysql+pymysql://root:root@localhost/services' + SQLALCHEMY_TRACK_MODIFICATIONS = False diff --git a/migrations/README b/migrations/README new file mode 100644 index 0000000..0e04844 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Single-database configuration for Flask. diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 0000000..ec9d45c --- /dev/null +++ b/migrations/alembic.ini @@ -0,0 +1,50 @@ +# A generic, single database configuration. + +[alembic] +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic,flask_migrate + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[logger_flask_migrate] +level = INFO +handlers = +qualname = flask_migrate + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..4c97092 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,113 @@ +import logging +from logging.config import fileConfig + +from flask import current_app + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) +logger = logging.getLogger('alembic.env') + + +def get_engine(): + try: + # this works with Flask-SQLAlchemy<3 and Alchemical + return current_app.extensions['migrate'].db.get_engine() + except (TypeError, AttributeError): + # this works with Flask-SQLAlchemy>=3 + return current_app.extensions['migrate'].db.engine + + +def get_engine_url(): + try: + return get_engine().url.render_as_string(hide_password=False).replace( + '%', '%%') + except AttributeError: + return str(get_engine().url).replace('%', '%%') + + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +config.set_main_option('sqlalchemy.url', get_engine_url()) +target_db = current_app.extensions['migrate'].db + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def get_metadata(): + if hasattr(target_db, 'metadatas'): + return target_db.metadatas[None] + return target_db.metadata + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, target_metadata=get_metadata(), literal_binds=True + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + # this callback is used to prevent an auto-migration from being generated + # when there are no changes to the schema + # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html + def process_revision_directives(context, revision, directives): + if getattr(config.cmd_opts, 'autogenerate', False): + script = directives[0] + if script.upgrade_ops.is_empty(): + directives[:] = [] + logger.info('No changes in schema detected.') + + conf_args = current_app.extensions['migrate'].configure_args + if conf_args.get("process_revision_directives") is None: + conf_args["process_revision_directives"] = process_revision_directives + + connectable = get_engine() + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=get_metadata(), + **conf_args + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 0000000..2c01563 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,24 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} diff --git a/migrations/versions/c1ef43f24351_.py b/migrations/versions/c1ef43f24351_.py new file mode 100644 index 0000000..0cde46f --- /dev/null +++ b/migrations/versions/c1ef43f24351_.py @@ -0,0 +1,56 @@ +"""empty message + +Revision ID: c1ef43f24351 +Revises: +Create Date: 2024-06-21 19:16:36.942400 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'c1ef43f24351' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('service', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('name', sa.String(length=64), nullable=False), + sa.Column('description', sa.Text(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('service', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_service_name'), ['name'], unique=True) + + op.create_table('status', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.Column('name', sa.String(length=32), nullable=False), + sa.Column('service_id', sa.Integer(), nullable=False), + sa.ForeignKeyConstraint(['service_id'], ['service.id'], ), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('status', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_status_name'), ['name'], unique=False) + batch_op.create_index(batch_op.f('ix_status_updated_at'), ['updated_at'], unique=False) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('status', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_status_updated_at')) + batch_op.drop_index(batch_op.f('ix_status_name')) + + op.drop_table('status') + with op.batch_alter_table('service', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_service_name')) + + op.drop_table('service') + # ### end Alembic commands ### diff --git a/task_python.py b/task_python.py new file mode 100644 index 0000000..ff4bd1b --- /dev/null +++ b/task_python.py @@ -0,0 +1,4 @@ +from app import create_app, db + + +app = create_app() \ No newline at end of file From 9137446cdd515cd922238c33ad6646560f64bacb Mon Sep 17 00:00:00 2001 From: Wiltort Date: Fri, 21 Jun 2024 21:16:39 +0500 Subject: [PATCH 2/2] requirements --- requirements.txt | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 requirements.txt diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..bb91f16 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,17 @@ +alembic==1.13.1 +blinker==1.8.2 +click==8.1.7 +colorama==0.4.6 +Flask==3.0.3 +Flask-Migrate==4.0.7 +Flask-SQLAlchemy==3.1.1 +greenlet==3.0.3 +itsdangerous==2.2.0 +Jinja2==3.1.4 +Mako==1.3.5 +MarkupSafe==2.1.5 +PyMySQL==1.1.1 +python-dotenv==1.0.1 +SQLAlchemy==2.0.31 +typing_extensions==4.12.2 +Werkzeug==3.0.3