Skip to content

Commit

Permalink
Добавил новый метод установки & Добавил анотацию типов данных
Browse files Browse the repository at this point in the history
  • Loading branch information
ZhymabekRoman committed Mar 12, 2021
1 parent 3356756 commit b6a55df
Show file tree
Hide file tree
Showing 9 changed files with 62 additions and 29 deletions.
Empty file modified .gitignore
100644 → 100755
Empty file.
Empty file modified LICENSE
100644 → 100755
Empty file.
10 changes: 9 additions & 1 deletion README.md
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,20 @@
Эта библиотека предоставляется Python интерфейс для никем незадокументированного и сделанного только для себя REST API Платонуса.

## Установка
В данное время Вы можете установить библиотеку из исходного кода с помощью:
В данное время Вы можете установить библиотеку из исходного кода с помощью pip3:
```
pytohn3 -m pip install https://github.com/ZhymabekRoman/platonus_api_wrapper/archive/main.zip
```

Или же напрямую через setup.py:
```
$ git clone https://github.com/ZhymabekRoman/platonus-api-wrapper --recursive
$ cd platonus-api-wrapper
$ python3 setup.py install
```

## Использование
Смотрите файл test.py

## Внесение своего вклада в проект
Внесение своего вклада максимально приветствуется!
6 changes: 4 additions & 2 deletions platonus_api_wrapper/__init__.py
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,7 @@
__license__ = "AGPL-3.0 License"
__email__ = "robanokssamit@yandex.com"

from platonus_api.main import PlatonusAPI
from platonus_api import exception
from .main import PlatonusAPI
import .exception

__all__ = [PlatonusAPI, exception]
Empty file modified platonus_api_wrapper/exception.py
100644 → 100755
Empty file.
65 changes: 42 additions & 23 deletions platonus_api_wrapper/main.py
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@
"""

import logging
from platonus_api import exception
import .exception
import pickle
from munch import munchify
from platonus_api.request import RequestSessionWrapper, URLNormalizer, URLValidator
from .request import RequestSessionWrapper, URLNormalizer

VERSION = "2.1"
BUILD_NUMBER = "101"
Expand All @@ -27,55 +27,68 @@ class PlatonusAPI(object):
Информации о REST API были получены путем обратной разработки веб приложении и Android клиента, так как в свободном доступе нету ни исходников Платонуса, ни документации (комерческая тайна).
REST API Платонуса скорее всего работает на Java (но это не точно)
Принимаемые аргументы:
platonus_url - URL адресс Платонуса
base_url - URL адресс Платонуса
language - язык = ru - Русскии
kz - Казахскии
en - English
context - корневой контекст URL адреса, где находится Платонус, обычно это /. К примеру колледж может на сайт example.kz установить Wordpress
и вести там главную страницу колледжа, а Платонус поставить на example.kz/platonus, вот как раз /platonus является контекстом Платонуса
check_API_compatibility - Проверка на совместимость данной библиотеки с Platonus сайтом.
context_path - корневой контекст URL адреса, где находится Платонус, обычно это /. К примеру колледж может на сайт example.kz установить Wordpress
и вести там главную страницу колледжа, а Платонус поставить на example.kz/platonus, вот как раз /platonus является контекстом Платонуса.
Более подробнее читайте здесь: https://medium.com/javascript-essentials/what-is-context-path-d442b3de164b
check_API_compatibility - Проверка на совместимость данной библиотеки с Platonus сайтом.
"""

def __init__(self, platonus_url, language: str = "ru", context: str = "/", check_API_compatibility: bool = True):
URLValidator(platonus_url)
base_platonus_url = URLNormalizer(platonus_url, context)
self.session = RequestSessionWrapper(base_platonus_url)
def __init__(self, base_url: str, language: str = "ru", context_path: str = "/", check_api_compatibility: bool = True):
platonus_url = URLNormalizer(base_url, context_path)
self.session = RequestSessionWrapper(platonus_url)
self.language = language
self.auth_token = None
if check_API_compatibility:
if check_api_compatibility:
self.check_compatibility_of_API_requests()

def load_session(self, session_file):
def load_session(self, session_file: str):
"""
Загружает сессию Платонуса из файла. Это позваляет каждый раз не логинится,
достаточно залогинится, экспортировать сессию через save_session и в нужый момент зайти в сессию через load_session.
ВНИМАНИЕ! У СЕСИИ ЕСТЬ ОПРЕДЕЛННЫЙ СРОК ДЕЙСТИИ, ПОКА НЕ ПОНЯТНО СКОЛЬКО ОНО ДЕЙСТВУЕТ, И КАК ЭТО ЗНАЧЕНИЕ ВЫСТАВЛЯЕТСЯ
"""
with open(session_file, 'rb') as f:
session, self.auth_token = pickle.load(f)
self.session.load_session(session)

def save_session(self, session_file):
def save_session(self, session_file: str):
"""
Загружает сессию Платонуса в файл. Это позваляет каждый раз не логинится,
достаточно залогинится, экспортировать сессию через save_session и в нужый момент зайти в сессию через load_session.
ВНИМАНИЕ! У СЕСИИ ЕСТЬ ОПРЕДЕЛННЫЙ СРОК ДЕЙСТИИ, ПОКА НЕ ПОНЯТНО СКОЛЬКО ОНО ДЕЙСТВУЕТ, И КАК ЭТО ЗНАЧЕНИЕ ВЫСТАВЛЯЕТСЯ
"""
with open(session_file, 'wb') as f:
pickle.dump((self.session.save_session(), self.auth_token), f)

def login(self, username=None, password=None, IIN=None):
def login(self, username: str = None, password: str = None, IIN: str = None):
"""
Авторизация в Платонус
Принимаемые аргументы:
username - логин
password - пароль
IIN - ИИН
"""
self._username = username
self._password = password
self._iin = IIN

auth_type = self.platonus_auth_type().value
__auth_type = self.platonus_auth_type().value

# Ждем с нетерпением нативный Switch-Case в Python 3.10, а то что-то мне не хочется плодить if-else =)
if auth_type == "1":
if __auth_type == "1":
if not username or not password or IIN:
raise exception.NotCorrectLoginCredentials("Укажите только username/password значения для авторизации в Платонус")
elif auth_type == "2":
elif __auth_type == "2":
if not username or not password or not IIN:
raise exception.NotCorrectLoginCredentials("Укажите только username/password/IIN значения для авторизации в Платонус")
elif auth_type == "3":
elif __auth_type == "3":
if username or not password or not IIN:
raise exception.NotCorrectLoginCredentials("Укажите только password/IIN значения для авторизации в Платонус")
elif auth_type == "4":
elif __auth_type == "4":
if username or password or IIN:
raise exception.NotCorrectLoginCredentials("Для авторизации в Платонус не требуется ввод учетных данных")

Expand All @@ -84,9 +97,9 @@ def login(self, username=None, password=None, IIN=None):
response = munchify(self.session.post('rest/api/login', json=params, headers=header).json())

if response.login_status == "invalid":
raise exception.NotCorrectLoginCredentials(response['message'])
raise exception.NotCorrectLoginCredentials(response.message)

# logging.info(f"Ваш авторизационный токен: {response['auth_token']}")
# logging.info(f"Ваш авторизационный токен: {response.auth_token}")
self.auth_token = response.auth_token
return response

Expand Down Expand Up @@ -128,7 +141,7 @@ def person_info(self):
response = self.session.get(f'rest/mobile/personInfo/{self.language}', headers={'token': self.auth_token}).json()
return munchify(response)

def student_tasks(self, count_in_part, part_number, start_date, end_date, recipient_status, topic="", study_group_id="-1", subject_id="-1", tutor_id="-1", term = "-1", year="-1"):
def student_tasks(self, count_in_part, part_number, start_date, end_date, recipient_status, topic="", study_group_id="-1", subject_id="-1", tutor_id="-1", term="-1", year="-1"):
"""Возвращяет все задания ученика"""
params = dict(countInPart=count_in_part, endDate=end_date, partNumber=part_number, recipientStatus=recipient_status, startDate=start_date, studyGroupID=study_group_id, subjectID=subject_id, term=term, topic=topic, tutorID=tutor_id, year=year)
return self.session.post(f'rest/assignments/studentTasks/-1/{self.language_num}', headers={'token': self.auth_token}, json=params).json()
Expand Down Expand Up @@ -251,8 +264,14 @@ def language_num(self):
elif self.language == "en":
language = "3"
else:
pass
raise ValueError(f"Unsupported language: {self.language}")
return language

@property
def is_authed(self):
"""Checks whether credentials were passed."""

return True if self._username and self._password else False

def logout(self):
self.session.post('rest/api/logout/', headers={'token': self.auth_token})
8 changes: 5 additions & 3 deletions platonus_api_wrapper/request.py
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import logging
import requests
from urllib.parse import urlsplit, urlparse
from platonus_api import exception
import .exception
from requests.adapters import HTTPAdapter

logging.basicConfig(level=logging.INFO)
Expand All @@ -20,7 +20,7 @@ def __init__(self, base_url, request_retries=3):

def request(self, method, url, *args, **kwargs):
response = self.session.request(method, f"{self.base_url}{url}", *args, **kwargs, timeout=10.0)
request_inf = f"URL: {url}, status code: {response.status_code}, {method} response contetnt: {response.content}"
request_info = f"URL: {url}, status code: {response.status_code}, {method} response contetnt: {response.content}"

if response.status_code == 401:
raise exception.InvalidToken("Seems login session is timeout")
Expand All @@ -32,7 +32,7 @@ def request(self, method, url, *args, **kwargs):

#response.raise_for_status()
response.encoding = 'utf-8'
#logging.info(request_inf)
#logging.info(request_info)
return response

def post(self, url, *args, **kwargs):
Expand Down Expand Up @@ -97,6 +97,8 @@ def URLValidator(url):
raise exception.InvalidURL("URL адрес сайта превышает 253 символов")

def URLNormalizer(url, context):
URLValidator(url)

parsed_url = urlparse(url)
result = '{uri.scheme}://{uri.netloc}{context}'.format(uri=parsed_url, context=context)
return result
2 changes: 2 additions & 0 deletions setup.py
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from setuptools import setup
from os.path import join, dirname
import sys
assert sys.version_info[0] == 3, "Platonus API Wrapper requires Python 3.x"

setup(
name='platonus_api_wrapper',
Expand Down
Empty file modified test.py
100644 → 100755
Empty file.

0 comments on commit b6a55df

Please sign in to comment.