From 60d29724b614bd25934666b8d86e730da23ba114 Mon Sep 17 00:00:00 2001 From: Ilya Sapunov Date: Tue, 11 Mar 2025 20:32:16 +0300 Subject: [PATCH] Added docs generator, splitted methods --- .gitignore | 3 ++ docs/Makefile | 20 ++++++++ docs/conf.py | 39 +++++++++++++++ docs/index.rst | 19 ++++++++ docs/make.bat | 35 ++++++++++++++ docs/setup.rst | 30 ++++++++++++ docs/usage.rst | 46 ++++++++++++++++++ kontur_focus/__init__.py | 3 +- kontur_focus/focus.py | 82 ++++++++++++++++++-------------- kontur_focus/focus_compliance.py | 0 kontur_focus/req.py | 35 ++++++++++++++ requirements.txt | 3 +- 12 files changed, 278 insertions(+), 37 deletions(-) create mode 100644 docs/Makefile create mode 100644 docs/conf.py create mode 100644 docs/index.rst create mode 100644 docs/make.bat create mode 100644 docs/setup.rst create mode 100644 docs/usage.rst create mode 100644 kontur_focus/focus_compliance.py create mode 100644 kontur_focus/req.py diff --git a/.gitignore b/.gitignore index 4a187df..75a7cf4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ +# OS files +.DS_Store + ### IDEA files .idea kontur-focus-lib.iml diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..d4bb2cb --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line, and also +# from the environment for the first two. +SPHINXOPTS ?= +SPHINXBUILD ?= sphinx-build +SOURCEDIR = . +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..75ddb8a --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,39 @@ +# Configuration file for the Sphinx documentation builder. +# +# For the full list of built-in configuration values, see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +# -- Project information ----------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information + +project = 'Kontur Focus Library' +copyright = '2025, Ilya Sapunov' +author = 'Ilya Sapunov' +release = '0.1.0' + +# -- General configuration --------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration +import sys +from pathlib import Path + +sys.path.insert(0, str(Path('..', '..', 'kontur-focus-lib').resolve())) + +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.viewcode', + 'sphinx.ext.todo', + 'sphinx.ext.coverage' +] + +templates_path = ['_templates'] +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +language = 'ru' +todo_include_todos = True +add_module_names = False + +# -- Options for HTML output ------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output + +html_theme = 'alabaster' +html_static_path = ['_static'] diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..39c6120 --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,19 @@ +.. Kontur Focus Library documentation master file, created by + sphinx-quickstart on Mon Mar 10 17:54:03 2025. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Kontur Focus Library documentation +================================== + +Add your content using ``reStructuredText`` syntax. See the +`reStructuredText `_ +documentation for details. + + +.. toctree:: + :maxdepth: 2 + :caption: Contents: + + setup + usage diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 0000000..32bb245 --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,35 @@ +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set SOURCEDIR=. +set BUILDDIR=_build + +%SPHINXBUILD% >NUL 2>NUL +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.https://www.sphinx-doc.org/ + exit /b 1 +) + +if "%1" == "" goto help + +%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% +goto end + +:help +%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% + +:end +popd diff --git a/docs/setup.rst b/docs/setup.rst new file mode 100644 index 0000000..160958e --- /dev/null +++ b/docs/setup.rst @@ -0,0 +1,30 @@ +========= +Установка +========= + +Для установки необходимо иметь доступ в корпоративный `Gitlab `_, чтобы получить доступ к Registry PyPi. + +Установка через pip +------------------- + +Выполните ``pip install kontur-focus --index-url https://__token__:@git.selectel.org/api/v4/projects/6350/packages/pypi/simple`` + +Где `` - `персональный токен `_ доступа Gitlab. + +Использование requirements.txt +------------------------------ + +Перед использованием необходимо настроить Registry. + +Создайте файл `.pypirc` в папке пользователя и добавьте параметры репозитория: + +.. code-block:: console + + [gitlab] + repository = https://git.selectel.org/api/v4/projects/6350/packages/pypi + username = __token__ + password = + +Более подробно `тут `_. + +После выполните ``pip install -r requirements.txt`` diff --git a/docs/usage.rst b/docs/usage.rst new file mode 100644 index 0000000..2b053a3 --- /dev/null +++ b/docs/usage.rst @@ -0,0 +1,46 @@ +============= +Использование +============= + +Подготовка +---------- + +Создайте файл `.env` или добавьте в существующий параметры: + +- `FOCUS_BASE_URL=` +- `FOCUS_ACCESS_KEY=` + +Где `kontur_url` - адрес REST API Контур.Фокус. Например, `https://focus-api.kontur.ru/api3`. + +А `FOCUS_ACCESS_KEY` - секретный ключ доступа к REST API Контур.Фокус. + +Инициализация +------------- + +.. code-block:: python + + from kontur_focus import Focus + + focus = Focus(inn='', ogrn='') + +Обязательный параметр - **ИНН**. + + +Основные методы +--------------- + +Пример использования методов: + +.. code-block:: python + + focus.base_info() + +.. autofunction:: kontur_focus.Focus.base_info() + +.. autofunction:: kontur_focus.Focus.advanced_info() + +.. autofunction:: kontur_focus.Focus.excerpt(path=None) + +.. autofunction:: kontur_focus.Focus.founders_history() + +.. autofunction:: kontur_focus.Focus.foreign_representatives() diff --git a/kontur_focus/__init__.py b/kontur_focus/__init__.py index 7fd271f..9f41461 100644 --- a/kontur_focus/__init__.py +++ b/kontur_focus/__init__.py @@ -1,4 +1,5 @@ from .focus import Focus +from .req import Request from .government_lists import gl -__all__ = [Focus, gl] +__all__ = [Focus, Request, gl] diff --git a/kontur_focus/focus.py b/kontur_focus/focus.py index 5702da2..2fe6a14 100644 --- a/kontur_focus/focus.py +++ b/kontur_focus/focus.py @@ -2,45 +2,47 @@ import requests import os from dotenv import load_dotenv from kontur_focus.government_lists import gl +from kontur_focus.req import Request -class Focus: - _base_url = None - _access_key = None - _inn = None - _orgn = None +class Focus(Request): _basedir = os.path.abspath(os.path.dirname(__file__)) def __init__(self, inn: str, ogrn: str = None): load_dotenv() - self._base_url = os.environ.get('BASE_URL') - self._access_key = os.environ.get('ACCESS_KEY') - self._inn = inn - self._orgn = ogrn - - def _r_get(self, path: str): - full_url = f'{self._base_url}{path}' - payload = {'key': self._access_key, 'inn': self._inn, 'ogrn': self._orgn} - - try: - response = requests.get(url=full_url, params=payload) - - if response.headers['Content-Type'] == 'application/pdf': - return response - else: - return response.json() - except Exception: - return 'Request error!' + super().__init__( + base_url=os.environ.get('FOCUS_BASE_URL'), + access_key=os.environ.get('FOCUS_ACCESS_KEY'), + inn=inn, + ogrn=ogrn + ) def base_info(self): - return self._r_get('/req') + """Выгрузка базовых реквизитов Российских юридических лиц и индивидуальных предпринимателей + + :return: Информация о ЮЛ + :rtype: str + """ + return self.get(path='/req') def advanced_info(self): - return self._r_get('/egrDetails') + """Расширенные сведения на основе ЕГРЮЛ/ЕГРИП - def excerpt(self, path=None): - response = self._r_get('/excerpt') - filename = f'{self._inn}_report.pdf' + :return: Информация о ЮЛ + :rtype: str + """ + return self.get('/egrDetails') + + def excerpt(self, path: str = None): + """Выписка из ЕГРЮЛ/ЕГРИП + + :param path: Путь выгрузки файла. Если не указан, выгружается в текущий каталог. + :type path: str, необязательный + :return: Результат и путьвыгрузки + :rtype: str + """ + response = self.get('/excerpt') + filename = f'{self.inn}_report.pdf' if not path: file_path = os.path.join(self._basedir, filename) @@ -51,18 +53,28 @@ class Focus: with open(file_path, mode='wb') as file: file.write(response.content) - return 'File saved' + return f'File {file_path} saved' except Exception: return 'Saving error!' def founders_history(self): - return self._r_get('/foundersHistory') + """История владения организацией + + :return: Набор полей с информацией об изменениях + :rtype: str + """ + return self.get('/foundersHistory') def foreign_representatives(self): - return self._r_get('/foreignRepresentatives') + """Иностранные представительства и филиалы - def full_analytics(self): - return self._r_get('/analytics') + :return: Набор данных о представительствах + :rtype: str + """ + return self.get('/foreignRepresentatives') + + def full_analytics(self): # DEPRECATED + return self.get('/analytics') @staticmethod def government_lists(): @@ -78,9 +90,9 @@ class Focus: :return: json """ if not list_name: - return self._r_get('/analyticLists') + return self.get('/analyticLists') else: - data = self._r_get('/analyticLists')[0]['listsEntries'] + data = self.get('/analyticLists')[0]['listsEntries'] list_id = next(item['uid'] for item in gl if item['name'] == list_name) return next(lst['isInList'] for lst in data if lst['id'] == list_id) diff --git a/kontur_focus/focus_compliance.py b/kontur_focus/focus_compliance.py new file mode 100644 index 0000000..e69de29 diff --git a/kontur_focus/req.py b/kontur_focus/req.py new file mode 100644 index 0000000..f82a167 --- /dev/null +++ b/kontur_focus/req.py @@ -0,0 +1,35 @@ +import requests +from requests.exceptions import RequestException + + +class Request: + """Base request class, which uses 'requests' library + + :return: Request result + :rtype: JSON or PDF file + """ + base_url = None + _access_key = None + content_type = None + inn = None + ogrn = None + + def __init__(self, base_url: str, access_key: str, inn: str = None, ogrn: str = None): + self.base_url = base_url + self._access_key = access_key + self.inn = inn + self.ogrn = ogrn + + def get(self, path: str): + full_url = f'{self.base_url}{path}' + payload = {'key': self._access_key, 'inn': self.inn, 'ogrn': self.ogrn} + + try: + response = requests.get(url=full_url, params=payload) + + if response.headers['Content-Type'] == 'application/pdf': + return response + else: + return response.json() + except RequestException as e: + return f'Error: {e}' diff --git a/requirements.txt b/requirements.txt index a57ddfd..da61026 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,5 @@ requests python-dotenv twine -wheel \ No newline at end of file +wheel +sphinx \ No newline at end of file