From 042e59a989d65c913a27bf3bd1347aec7730c68c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D1=82=D0=B5=D0=BF=D0=B0=D0=BD=D0=B5=D0=BD=D0=BA?= =?UTF-8?q?=D0=BE=20=D0=9E=D0=BB=D1=8C=D0=B3=D0=B0?= Date: Mon, 1 Mar 2021 20:50:25 +0300 Subject: [PATCH 1/7] Change conf --- docs/Makefile | 3 ++ docs/source/conf.py | 89 -------------------------------------------- docs/source/todo.rst | 2 +- 3 files changed, 4 insertions(+), 90 deletions(-) delete mode 100644 docs/source/conf.py diff --git a/docs/Makefile b/docs/Makefile index d0c3cbf..461302a 100644 --- a/docs/Makefile +++ b/docs/Makefile @@ -18,3 +18,6 @@ help: # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +spelling: + $(SPHINXBUILD) -b spelling -W $(ALLSPHINXOPTS) $(BUILDDIR)/spelling diff --git a/docs/source/conf.py b/docs/source/conf.py deleted file mode 100644 index 438d5a4..0000000 --- a/docs/source/conf.py +++ /dev/null @@ -1,89 +0,0 @@ -# Configuration file for the Sphinx documentation builder. -# -# This file only contains a selection of the most common options. For a full -# list see the documentation: -# https://www.sphinx-doc.org/en/master/usage/configuration.html - -# -- Path setup -------------------------------------------------------------- - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -# -import os -import sys -sys.path.insert(0, os.path.abspath('../../')) - -import django -os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'access_controller.settings') -django.setup() - -# -- Project information ----------------------------------------------------- - -project = 'ZenDesk Access Controller' -copyright = '2021, SHP S101, group 2' -author = 'SHP S101, group 2' - -# The full version, including alpha/beta/rc tags -release = 'v0.01' - - -# -- General configuration --------------------------------------------------- - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - 'sphinx.ext.todo', - 'sphinx.ext.autodoc', - 'sphinx.ext.intersphinx', - 'sphinx.ext.viewcode', - 'sphinx_rtd_theme', -] - -# Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = 'ru' - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -# This pattern also affects html_static_path and html_extra_path. -exclude_patterns = [] - - -# -- Options for HTML output ------------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -# -html_theme = "sphinx_rtd_theme" - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] - - -# -- Extension configuration ------------------------------------------------- - -# -- Options for intersphinx extension --------------------------------------- - -# Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = { - 'https://docs.python.org/3/': None, - 'django': ( - 'https://docs.djangoproject.com/en/dev/', - 'https://docs.djangoproject.com/en/dev/_objects/' - ), -} - -# -- Options for todo extension ---------------------------------------------- - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = True diff --git a/docs/source/todo.rst b/docs/source/todo.rst index a8d024b..ad6e4ed 100644 --- a/docs/source/todo.rst +++ b/docs/source/todo.rst @@ -1,5 +1,5 @@ Что необходимо доделать? -======================= +======================== From cd504275321e476a6fd0ccfdaa99f761604c61c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D1=82=D0=B5=D0=BF=D0=B0=D0=BD=D0=B5=D0=BD=D0=BA?= =?UTF-8?q?=D0=BE=20=D0=9E=D0=BB=D1=8C=D0=B3=D0=B0?= Date: Mon, 1 Mar 2021 20:52:39 +0300 Subject: [PATCH 2/7] Change conf --- docs/source/conf.py | 201 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 201 insertions(+) create mode 100644 docs/source/conf.py diff --git a/docs/source/conf.py b/docs/source/conf.py new file mode 100644 index 0000000..6c8988c --- /dev/null +++ b/docs/source/conf.py @@ -0,0 +1,201 @@ +# Configuration file for the Sphinx documentation builder. +# +# This file only contains a selection of the most common options. For a full +# list see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +# -- Path setup -------------------------------------------------------------- + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +import os +import sys +import importlib +import inspect +sys.path.insert(0, os.path.abspath('../../')) + +import django +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'access_controller.settings') +os.environ.setdefault('DJANGO_CONFIGURATION', 'Dev') + +# Fix Django's FileFields +from django.db.models.fields.files import FileDescriptor +FileDescriptor.__get__ = lambda self, *args, **kwargs: self +from django.db.models.manager import ManagerDescriptor +ManagerDescriptor.__get__ = lambda self, *args, **kwargs: self.manager + + +# Stop Django from executing DB queries +from django.db.models.query import QuerySet +QuerySet.__repr__ = lambda self: self.__class__.__name__ +try: + import enchant # NoQA +except ImportError: + enchant = None + +django.setup() + +# -- Project information ----------------------------------------------------- + +project = 'ZenDesk Access Controller' +copyright = '2021, SHP S101, group 2' +author = 'SHP S101, group 2' + +# The full version, including alpha/beta/rc tags +release = 'v0.01' + +#Django sphinx setup by https://gist.github.com/codingjoe/314bda5a07ff3b41f247 + +# -- General configuration --------------------------------------------------- + +def process_django_models(app, what, name, obj, options, lines): + """Append params from fields to model documentation.""" + from django.utils.encoding import force_text + from django.utils.html import strip_tags + from django.db import models + + spelling_white_list = ['', '.. spelling::'] + + if inspect.isclass(obj) and issubclass(obj, models.Model): + for field in obj._meta.fields: + help_text = strip_tags(force_text(field.help_text)) + verbose_name = force_text(field.verbose_name).capitalize() + + if help_text: + lines.append(':param %s: %s - %s' % (field.attname, verbose_name, help_text)) + else: + lines.append(':param %s: %s' % (field.attname, verbose_name)) + + if enchant is not None: + from enchant.tokenize import basic_tokenize + + words = verbose_name.replace('-', '.').replace('_', '.').split('.') + words = [s for s in words if s != ''] + for word in words: + spelling_white_list += [" %s" % ''.join(i for i in word if not i.isdigit())] + spelling_white_list += [" %s" % w[0] for w in basic_tokenize(word)] + + field_type = type(field) + module = field_type.__module__ + if 'django.db.models' in module: + # scope with django.db.models * imports + module = 'django.db.models' + lines.append(':type %s: %s.%s' % (field.attname, module, field_type.__name__)) + if enchant is not None: + lines += spelling_white_list + return lines + + +def process_modules(app, what, name, obj, options, lines): + """Add module names to spelling white list.""" + if what != 'module': + return lines + from enchant.tokenize import basic_tokenize + + spelling_white_list = ['', '.. spelling::'] + words = name.replace('-', '.').replace('_', '.').split('.') + words = [s for s in words if s != ''] + for word in words: + spelling_white_list += [" %s" % ''.join(i for i in word if not i.isdigit())] + spelling_white_list += [" %s" % w[0] for w in basic_tokenize(word)] + lines += spelling_white_list + return lines + + +def skip_queryset(app, what, name, obj, skip, options): + """Skip queryset subclasses to avoid database queries.""" + from django.db import models + if isinstance(obj, (models.QuerySet, models.manager.BaseManager)) or name.endswith('objects'): + return True + return skip + + +def setup(app): + # Register the docstring processor with sphinx + app.connect('autodoc-process-docstring', process_django_models) + app.connect('autodoc-skip-member', skip_queryset) + if enchant is not None: + app.connect('autodoc-process-docstring', process_modules) + + + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.todo', + 'sphinx.ext.autodoc', + 'sphinx.ext.intersphinx', + 'sphinx.ext.viewcode', + 'sphinx_rtd_theme', + 'sphinx.ext.graphviz', + 'sphinx.ext.napoleon', + 'sphinx.ext.inheritance_diagram', + +] + +if enchant is not None: + extensions.append('sphinxcontrib.spelling') + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = 'ru' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path. +exclude_patterns = [] + + +# -- Options for HTML output ------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = "sphinx_rtd_theme" + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + + +# -- Extension configuration ------------------------------------------------- + +# -- Options for intersphinx extension --------------------------------------- + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + 'https://docs.python.org/3/': None, + 'django': ( + 'https://docs.djangoproject.com/en/dev/', + 'https://docs.djangoproject.com/en/dev/_objects/' + ), + 'djangoextensions': ('https://django-extensions.readthedocs.org/en/latest/', None), + 'geoposition': ('https://django-geoposition.readthedocs.org/en/latest/', None), + 'braces': ('https://django-braces.readthedocs.org/en/latest/', None), + 'select2': ('https://django-select2.readthedocs.org/en/latest/', None), + 'celery': ('https://celery.readthedocs.org/en/latest/', None), +} + +autodoc_default_flags = ['members'] + +# spell checking +spelling_lang = 'en_US' +spelling_word_list_filename = 'spelling_wordlist.txt' +spelling_show_suggestions = True +spelling_ignore_pypi_package_names = True + +# -- Options for todo extension ---------------------------------------------- + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True From a64e641a33e0d5eb623e15ad227098432ed8c2e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D1=82=D0=B5=D0=BF=D0=B0=D0=BD=D0=B5=D0=BD=D0=BA?= =?UTF-8?q?=D0=BE=20=D0=9E=D0=BB=D1=8C=D0=B3=D0=B0?= Date: Mon, 1 Mar 2021 21:18:27 +0300 Subject: [PATCH 3/7] Change conf using github snippet --- docs/source/conf.py | 1 + main/models.py | 1 + 2 files changed, 2 insertions(+) diff --git a/docs/source/conf.py b/docs/source/conf.py index 6c8988c..b70857e 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -85,6 +85,7 @@ def process_django_models(app, what, name, obj, options, lines): lines.append(':type %s: %s.%s' % (field.attname, module, field_type.__name__)) if enchant is not None: lines += spelling_white_list + print('ok') return lines diff --git a/main/models.py b/main/models.py index b7b30dd..2cf76ac 100644 --- a/main/models.py +++ b/main/models.py @@ -15,6 +15,7 @@ class UserProfile(models.Model): :type image: :class:`img` :param name: Имя пользователя на нашем сайте :type name: :class:`str` + """ user = models.OneToOneField(to=User, on_delete=models.CASCADE) From f9e6b79f0124755a90bb7b48f9f5e5104c260d7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D1=82=D0=B5=D0=BF=D0=B0=D0=BD=D0=B5=D0=BD=D0=BA?= =?UTF-8?q?=D0=BE=20=D0=9E=D0=BB=D1=8C=D0=B3=D0=B0?= Date: Tue, 2 Mar 2021 09:52:18 +0300 Subject: [PATCH 4/7] Change models documentation using snippets --- main/models.py | 34 +++++++++------------------------- 1 file changed, 9 insertions(+), 25 deletions(-) diff --git a/main/models.py b/main/models.py index 2cf76ac..8665570 100644 --- a/main/models.py +++ b/main/models.py @@ -8,20 +8,12 @@ class UserProfile(models.Model): """ Модель профиля пользователя - :param user: OneToOneField к модели :class:`django.contrib.auth.models.User` - :param role: Код роли пользователя - :type role: :class:`integer` - :param image: Аватарка - :type image: :class:`img` - :param name: Имя пользователя на нашем сайте - :type name: :class:`str` - """ - user = models.OneToOneField(to=User, on_delete=models.CASCADE) - role = models.CharField(default='None', max_length=100) - image = models.URLField(null=True, blank=True) - name = models.CharField(default='None', max_length=100) + user = models.OneToOneField(to=User, on_delete=models.CASCADE, help_text='Пользователь') + role = models.CharField(default='None', max_length=100, help_text='Код роли пользователя') + image = models.URLField(null=True, blank=True, help_text='Аватарка') + name = models.CharField(default='None', max_length=100, help_text='Имя пользователя на нашем сайте') @receiver(post_save, sender=User) @@ -39,17 +31,9 @@ class RoleChangeLogs(models.Model): """ Модель для логирования изменений ролей пользователя - :param user: Пользователь, которому присвоили другую роль, ForeignKey к модели :class:`django.contrib.auth.models.User` - :param name: Имя пользователя - :type name: :class:`str` - :param new_role: Присвоенная роль - :type new_role: :class:`str` - :param change_time: Дата изменения роли` - :type change_time: :class:`datetime.datetime` - :param changed_by: Кем была изменена роль, ForeignKey к модели :class:`django.contrib.auth.models.User` """ - user = models.ForeignKey(to=User, on_delete=models.CASCADE) - name = models.TextField() - new_role = models.TextField() - change_time = models.DateTimeField() - changed_by = models.ForeignKey(to=User, on_delete=models.CASCADE, related_name='changed_by') + user = models.ForeignKey(to=User, on_delete=models.CASCADE, help_text='Пользователь, которому присвоили другую роль') + name = models.TextField(help_text='Имя пользователя') + new_role = models.TextField(help_text='Присвоенная роль') + change_time = models.DateTimeField(help_text='Дата и время изменения роли') + changed_by = models.ForeignKey(to=User, on_delete=models.CASCADE, related_name='changed_by', help_text='Кем была изменена роль') From 4a9b3d71a42678327d8a8861f3376d281f0d7f9b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D1=82=D0=B5=D0=BF=D0=B0=D0=BD=D0=B5=D0=BD=D0=BA?= =?UTF-8?q?=D0=BE=20=D0=9E=D0=BB=D1=8C=D0=B3=D0=B0?= Date: Tue, 2 Mar 2021 12:30:56 +0300 Subject: [PATCH 5/7] Add typehints --- docs/source/conf.py | 6 ++++++ main/extra_func.py | 31 ++++++++++--------------------- 2 files changed, 16 insertions(+), 21 deletions(-) diff --git a/docs/source/conf.py b/docs/source/conf.py index b70857e..fdcc4e4 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -134,6 +134,7 @@ extensions = [ 'sphinx.ext.graphviz', 'sphinx.ext.napoleon', 'sphinx.ext.inheritance_diagram', + 'sphinx_autodoc_typehints' ] @@ -200,3 +201,8 @@ spelling_ignore_pypi_package_names = True # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True + +set_type_checking_flag = True +typehints_fully_qualified = True +always_document_param_types = True +typehints_document_rtype = True diff --git a/main/extra_func.py b/main/extra_func.py index 20c3712..2d780b8 100644 --- a/main/extra_func.py +++ b/main/extra_func.py @@ -20,65 +20,54 @@ class ZendeskAdmin: :type token: :class:`str` :param password: Пароль администратора, указанный в env :type password: :class:`str` + """ - credentials = { + credentials:dict = { 'subdomain': 'ngenix1612197338' } - email = os.getenv('ACCESS_CONTROLLER_API_EMAIL') - token = os.getenv('ACCESS_CONTROLLER_API_TOKEN') - password = os.getenv('ACCESS_CONTROLLER_API_PASSWORD') + email: str = os.getenv('ACCESS_CONTROLLER_API_EMAIL') + token: str = os.getenv('ACCESS_CONTROLLER_API_TOKEN') + password: str = os.getenv('ACCESS_CONTROLLER_API_PASSWORD') def __init__(self): self.create_admin() def check_user(self, email: str) -> bool: """ - Функция **check_user** осуществляет проверку существования пользователя в Zendesk + Функция **check_user** осуществляет проверку существования пользователя в Zendesk по email - :param email: Электронная почта пользователя - :type email: :class:`email` - :return: True, если существует, иначе False - :rtype: :class:`bool` """ return True if self.admin.search(email, type='user') else False def get_user_name(self, email: str) -> str: """ - Функция **get_user_name** возвращает имя пользователя + Функция **get_user_name** возвращает имя пользователя по его email - :param user_name: Имя пользователя - :type user_name: :class:`str` """ user = self.admin.users.search(email).values[0] return user.name def get_user_role(self, email: str) -> str: """ - Функция **get_user_role** возвращает роль пользователя + Функция **get_user_role** возвращает роль пользователя по его email - :param user_role: Роль пользователя - :type user_role: :class:`str` """ user = self.admin.users.search(email).values[0] return user.role def get_user_id(self, email: str) -> str: """ - Функция **get_user_id** возвращает id пользователя + Функция **get_user_id** возвращает id пользователя по его email - :param user_id: ID пользователя - :type user_id: :class:`str` """ user = self.admin.users.search(email).values[0] return user.id def get_user_image(self, email: str) -> str: """ - Функция **get_user_image** возвращает аватар пользователя + Функция **get_user_image** возвращает аватар пользователя по его email - :param user_image: Аватар пользователя - :type user_image: :class:`img` """ user = self.admin.users.search(email).values[0] return user.photo['content_url'] if user.photo else None From edbe0a66af24762b70678d175f30b90f20dc35d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D1=82=D0=B5=D0=BF=D0=B0=D0=BD=D0=B5=D0=BD=D0=BA?= =?UTF-8?q?=D0=BE=20=D0=9E=D0=BB=D1=8C=D0=B3=D0=B0?= Date: Tue, 2 Mar 2021 15:10:28 +0300 Subject: [PATCH 6/7] Change extra_func documentation --- main/extra_func.py | 65 +++++++++++++++++++++------------------------- 1 file changed, 30 insertions(+), 35 deletions(-) diff --git a/main/extra_func.py b/main/extra_func.py index 2d780b8..9e104be 100644 --- a/main/extra_func.py +++ b/main/extra_func.py @@ -13,9 +13,9 @@ class ZendeskAdmin: Класс **ZendeskAdmin** существует, чтобы в каждой фунциии отдельно не проверять аккаунт администратора :param credentials: Полномочия (первым указывается учетная запись организации в Zendesk) - :type credentials: :class:`list of dictionaries` + :type credentials: :class:`dict` :param email: Email администратора, указанный в env - :type email: :class:`email` + :type email: :class:`str` :param token: Токен администратора (формируется в Zendesk, указывается в env) :type token: :class:`str` :param password: Пароль администратора, указанный в env @@ -23,7 +23,7 @@ class ZendeskAdmin: """ - credentials:dict = { + credentials: dict = { 'subdomain': 'ngenix1612197338' } email: str = os.getenv('ACCESS_CONTROLLER_API_EMAIL') @@ -36,14 +36,12 @@ class ZendeskAdmin: def check_user(self, email: str) -> bool: """ Функция **check_user** осуществляет проверку существования пользователя в Zendesk по email - """ return True if self.admin.search(email, type='user') else False def get_user_name(self, email: str) -> str: """ Функция **get_user_name** возвращает имя пользователя по его email - """ user = self.admin.users.search(email).values[0] return user.name @@ -51,7 +49,6 @@ class ZendeskAdmin: def get_user_role(self, email: str) -> str: """ Функция **get_user_role** возвращает роль пользователя по его email - """ user = self.admin.users.search(email).values[0] return user.role @@ -59,7 +56,6 @@ class ZendeskAdmin: def get_user_id(self, email: str) -> str: """ Функция **get_user_id** возвращает id пользователя по его email - """ user = self.admin.users.search(email).values[0] return user.id @@ -67,23 +63,29 @@ class ZendeskAdmin: def get_user_image(self, email: str) -> str: """ Функция **get_user_image** возвращает аватар пользователя по его email - """ user = self.admin.users.search(email).values[0] return user.photo['content_url'] if user.photo else None def get_user(self, email: str) -> str: + """ + Функция **get_user** возвращает пользователя (объект) по его email + """ return self.admin.users.search(email).values[0] def get_user_org(self, email: str) -> str: + """ + Функция **get_user_org** возвращает организацию, к которой относится пользователь по его email + """ user = self.admin.users.search(email).values[0] return user.organization.name - def create_admin(self) -> None: + def create_admin(self) -> Zenpy: """ Функция **Create_admin()** создает администратора, проверяя наличие вводимых данных в env. :param credentials: В список полномочий администратора вносятся email, token, password из env + :type credentials: :class:`dict` :raise: :class:`ValueError`: исключение, вызываемое если email не введен в env :raise: :class:`APIException`: исключение, вызываемое если пользователя с таким email не существует в Zendesk """ @@ -105,34 +107,43 @@ class ZendeskAdmin: raise ValueError('invalid access_controller`s login data') -def update_role(user_profile, role): +def update_role(user_profile: UserProfile, role: str) -> UserProfile: + """ + Функция **update_role** меняет роль пользователя. + """ zendesk = ZendeskAdmin() user = zendesk.get_user(user_profile.user.email) user.custom_role_id = role zendesk.admin.users.update(user) -def make_engineer(user_profile): +def make_engineer(user_profile: UserProfile) -> UserProfile: + """ + Функция **make_engineer** устанавливапет пользователю роль инженера. + """ update_role(user_profile, ROLES['engineer']) -def make_light_agent(user_profile): +def make_light_agent(user_profile: UserProfile) -> UserProfile: + """ + Функция **make_light_agent** устанавливапет пользователю роль легкого агента. + """ update_role(user_profile, ROLES['light_agent']) -def get_users_list(): +def get_users_list() -> list: + """ + Функция **get_users_list** возвращает список пользователей Zendesk, относящихся к организации. + """ zendesk = ZendeskAdmin() admin = zendesk.get_user(zendesk.email) org = next(zendesk.admin.users.organizations(user=admin)) return zendesk.admin.organizations.users(org) -def update_profile(user_profile: UserProfile): +def update_profile(user_profile: UserProfile) -> UserProfile: """ - Функция обновляет профиль пользователя в соотвтетствии с текущим в Zendesk - - :param user_profile: Объект профиля пользователя - :type user_profile: :class:`main.models.UserProfile` + Функция обновляет профиль пользователя в соотвтетствии с текущим в Zendesk """ user = ZendeskAdmin().get_user(user_profile.user.email) user_profile.name = user.name @@ -143,12 +154,7 @@ def update_profile(user_profile: UserProfile): def check_user_exist(email: str) -> bool: """ - Функция проверяет, существует ли пользователь - - :param email: Электронная почта пользователя - :type email: :class:`str` - :return: True, если существует, иначе False - :rtype: :class:`bool` + Функция проверяет, существует ли пользователь """ return ZendeskAdmin().check_user(email) @@ -156,11 +162,6 @@ def check_user_exist(email: str) -> bool: def get_user_organization(email: str) -> str: """ Функция возвращает организацию пользователя - - :param email: Электронная почта пользователя - :type email: :class:`str` - :return: Название организации - :rtype: :class:`str` """ return ZendeskAdmin().get_user_org(email) @@ -169,13 +170,7 @@ def check_user_auth(email: str, password: str) -> bool: """ Функция проверяет, верны ли входные данные - :param email: Электроная почта пользователя - :type email: :class:`str` - :param password: Пароль пользователя - :type password: :class:`str` - :return: True, если входные данные верны, иначе False :raise: :class:`APIException`: исключение, вызываемое если пользователь не аутентифицирован - :rtype: :class:`bool` """ creds = { 'email': email, From 525a5a61d226356187505ad459c39c2fede3b67f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D1=82=D0=B5=D0=BF=D0=B0=D0=BD=D0=B5=D0=BD=D0=BA?= =?UTF-8?q?=D0=BE=20=D0=9E=D0=BB=D1=8C=D0=B3=D0=B0?= Date: Tue, 2 Mar 2021 16:52:20 +0300 Subject: [PATCH 7/7] Change extra_func documentation --- main/extra_func.py | 2 +- main/forms.py | 15 +++++++++++---- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/main/extra_func.py b/main/extra_func.py index 9e104be..b07f242 100644 --- a/main/extra_func.py +++ b/main/extra_func.py @@ -78,7 +78,7 @@ class ZendeskAdmin: Функция **get_user_org** возвращает организацию, к которой относится пользователь по его email """ user = self.admin.users.search(email).values[0] - return user.organization.name + return user.organization def create_admin(self) -> Zenpy: """ diff --git a/main/forms.py b/main/forms.py index d80932c..176302e 100644 --- a/main/forms.py +++ b/main/forms.py @@ -6,11 +6,11 @@ from main.models import UserProfile class CustomRegistrationForm(RegistrationFormUniqueEmail): """ - Форма для регистрации :class:`django_registration.forms.RegistrationFormUniqueEmail` - с добавлением bootstrap-класса 'form-control' + Форма для регистрации :class:`django_registration.forms.RegistrationFormUniqueEmail` + с добавлением bootstrap-класса 'form-control' - :param password_zen: Поле для ввода пароля от Zendesk - :type password_zen: :class:`django.forms.CharField` + :param password_zen: Поле для ввода пароля от Zendesk + :type password_zen: :class:`django.forms.CharField` """ def __init__(self, *args, **kwargs): @@ -29,6 +29,13 @@ class CustomRegistrationForm(RegistrationFormUniqueEmail): class AdminPageUsers(forms.Form): + """ + Форма для установки статуса + + :param password_zen: Поле для ввода пароля от Zendesk + :type password_zen: :class:`django.forms.CharField` + """ + users = forms.ModelMultipleChoiceField( queryset=UserProfile.objects.filter(role='agent'), widget=forms.CheckboxSelectMultiple(