This commit is contained in:
Kavalar 2024-12-22 14:10:39 +03:00
commit 33229449f5
7 changed files with 238 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
__pycache__

23
BaseEntity.py Normal file
View File

@ -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

88
Connection.py Normal file
View File

@ -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

19
IgfClient.py Normal file
View File

@ -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)

7
__init__.py Normal file
View File

@ -0,0 +1,7 @@
from dotenv import dotenv_values
from igf_api.Connection import Connection
config = dotenv_values(".env")
connection = Connection(config=config)

74
entities/PiapiTask.py Normal file
View File

@ -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))

26
entities/TgBot.py Normal file
View File

@ -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