From 33229449f5631f41fd6176b182ef6e72dbafd0e8 Mon Sep 17 00:00:00 2001 From: Kavalar Date: Sun, 22 Dec 2024 14:10:39 +0300 Subject: [PATCH] first --- .gitignore | 1 + BaseEntity.py | 23 +++++++++++ Connection.py | 88 +++++++++++++++++++++++++++++++++++++++++++ IgfClient.py | 19 ++++++++++ __init__.py | 7 ++++ entities/PiapiTask.py | 74 ++++++++++++++++++++++++++++++++++++ entities/TgBot.py | 26 +++++++++++++ 7 files changed, 238 insertions(+) create mode 100644 .gitignore create mode 100644 BaseEntity.py create mode 100644 Connection.py create mode 100644 IgfClient.py create mode 100644 __init__.py create mode 100644 entities/PiapiTask.py create mode 100644 entities/TgBot.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ed8ebf5 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +__pycache__ \ No newline at end of file diff --git a/BaseEntity.py b/BaseEntity.py new file mode 100644 index 0000000..a8e352d --- /dev/null +++ b/BaseEntity.py @@ -0,0 +1,23 @@ +import jsonschema + + +class BaseEntity: + + def __init__(self, connection): + self.connection = connection + + def validate_dict(self, dictionary, schema): + # schema = { + # 'type': 'object', + # 'properties': { + # 'key1': {'type': 'integer'}, + # 'key2': {'type': 'string'} + # }, + # 'required': ['key1', 'key2'] + # } + try: + jsonschema.validate(dictionary, schema) + return True + except jsonschema.ValidationError as ex: + print(ex) + return False \ No newline at end of file diff --git a/Connection.py b/Connection.py new file mode 100644 index 0000000..2f791ce --- /dev/null +++ b/Connection.py @@ -0,0 +1,88 @@ +import time +from datetime import datetime, date +from requests.exceptions import HTTPError +import requests + + +class Connection: + + def __init__(self, config): + self._login = config['IGF_USER'] + self._password = config['IGF_PASS'] + self.url = config['IGF_URL'] + self.access_token = '' + self.access_token_expired_at = '' + + def login(self): + json_response = self.raw_request_without_auth(method="post", endpoint="/secure/auth", data={'username': self._login, 'password': self._password}) + + self.access_token = json_response['access_token'] + self.access_token_expired_at = json_response['access_token_expires_at'] + print('Login Success!', self.access_token, self.access_token_expired_at) + + def raw_request(self, method, endpoint, params=None, data=None): + # TODO доработать сравнение + access_token_expired_at_date, access_token_expired_at_time = self.access_token_expired_at.split(" ") + expired_at = datetime.strptime(access_token_expired_at_date, '%Y-%m-%d') + now = datetime.today() + if (expired_at < now): + print("exp") + self.login(self._login, self._password) + + if data is None: + data = {} + if params is None: + params = {} + + try: + response = requests.request(method=method, + url="{url}{endpoint}".format(url=self.url, endpoint=endpoint), + auth=BearerAuth(self.access_token), + params=params, + data=data + ) + + response.raise_for_status() + except HTTPError as http_err: + print(f'HTTP error occurred: {http_err}') # Python 3.6 + except Exception as err: + print(f'Other error occurred: {err}') # Python 3.6 + else: + json_response = response.json() + + return json_response + + def raw_request_without_auth(self, method, endpoint, params=None, data=None): + if data is None: + data = {} + if params is None: + params = {} + + try: + response = requests.request(method=method, + url="{url}{endpoint}".format(url=self.url, endpoint=endpoint), + params=params, + data=data + ) + + response.raise_for_status() + except HTTPError as http_err: + print(f'HTTP error occurred: {http_err}') # Python 3.6 + except Exception as err: + print(f'Other error occurred: {err}') # Python 3.6 + else: + json_response = response.json() + + return json_response + + def set_url(self, url: str): + self.url = url + + +class BearerAuth(requests.auth.AuthBase): + def __init__(self, token): + self.token = token + + def __call__(self, r): + r.headers["authorization"] = "Bearer " + self.token + return r diff --git a/IgfClient.py b/IgfClient.py new file mode 100644 index 0000000..8ff57c7 --- /dev/null +++ b/IgfClient.py @@ -0,0 +1,19 @@ +from igf_api.Connection import Connection +from igf_api.entities.PiapiTask import PiapiTask +from igf_api.entities.TgBot import TgBot +from igf_api import connection + + +class IgfClient: + + def __init__(self): + self.connection = connection + self.connection.login() + self.tgBot = TgBot(connection=self.connection) + self.piapiTask = PiapiTask(connection=self.connection) + + def login(self, login: str, password: str): + self.connection.login(login=login, password=password) + + def set_url(self, url: str): + self.connection.set_url(url=url) diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..9f6ef3c --- /dev/null +++ b/__init__.py @@ -0,0 +1,7 @@ +from dotenv import dotenv_values + +from igf_api.Connection import Connection + +config = dotenv_values(".env") + +connection = Connection(config=config) diff --git a/entities/PiapiTask.py b/entities/PiapiTask.py new file mode 100644 index 0000000..f80ae4d --- /dev/null +++ b/entities/PiapiTask.py @@ -0,0 +1,74 @@ +from igf_api.BaseEntity import BaseEntity + + +class PiapiTask(BaseEntity): + + def get_list(self): + return self.connection.raw_request(method='get', endpoint='/piapi') + + def get_one(self, data): + schema = { + 'type': 'object', + 'properties': { + 'bot_id': {'type': 'integer'}, + 'dialog_id': {'type': 'integer'}, + 'task_id': {"type": ["string", "null"]}, + 'model': {'type': 'string'}, + 'task_type': {'type': 'string'}, + 'prompt': {'type': 'string'}, + 'status': {'type': 'integer'}, + }, + 'required': [] + } + + if self.validate_dict(data, schema): + return self.connection.raw_request('get', '/piapi/get-one', params=data) + + return False + + def create(self, data): + schema = { + 'type': 'object', + 'properties': { + 'bot_id': {'type': 'integer'}, + 'dialog_id': {'type': 'integer'}, + 'task_id': {"type": ["string", "null"]}, + 'model': {'type': 'string'}, + 'task_type': {'type': 'string'}, + 'prompt': {'type': 'string'}, + 'status': {'type': 'integer'}, + }, + 'required': ['dialog_id', 'bot_id'] + } + + if self.validate_dict(data, schema): + return self.connection.raw_request('post', '/piapi', data=data) + + return False + + def update(self, id: int, data): + schema = { + 'type': 'object', + 'properties': { + 'bot_id': {'type': 'integer'}, + 'dialog_id': {'type': 'integer'}, + 'task_id': {"type": ["string", "null"]}, + 'model': {'type': 'string'}, + 'task_type': {'type': 'string'}, + 'prompt': {'type': 'string'}, + 'status': {'type': 'integer'}, + }, + 'required': [] + } + + if self.validate_dict(data, schema): + return self.connection.raw_request('post', '/piapi/update/{id}'.format(id=id), data=data) + + return False + + def to_archive_all_new(self, bot_id: int, dialog_id: int): + return self.connection.raw_request('get', '/piapi/to-archive-all-new/{bot_id}/{dialog_id}'.format(bot_id=bot_id, + dialog_id=dialog_id)) + + def get_new_tasks(self): + return self.connection.raw_request('get', '/piapi/find?status={status}'.format(status=1)) diff --git a/entities/TgBot.py b/entities/TgBot.py new file mode 100644 index 0000000..827a80d --- /dev/null +++ b/entities/TgBot.py @@ -0,0 +1,26 @@ +from igf_api.BaseEntity import BaseEntity + + +class TgBot(BaseEntity): + + def get_list(self): + return self.connection.raw_request(method='get', endpoint='/tg-bot') + + def create(self, data): + schema = { + 'type': 'object', + 'properties': { + 'bot_id': {'type': 'integer'}, + 'dialog_id': {'type': 'integer'}, + 'username': {'type': 'string'}, + 'first_name': {'type': 'string'}, + 'last_name': {'type': 'string'}, + 'status': {'type': 'integer'}, + }, + 'required': ['dialog_id', 'bot_id'] + } + + if self.validate_dict(data, schema): + return self.connection.raw_request('post', '/tg-bot', data=data) + + return False