Используйте Sphinx рекурсивно для автоматического создания документации API

Я хочу использовать автоматическое расширение Sphinx и шаблоны для рекурсивной генерации документов API из строк документации. Я хочу отдельные страницы для каждого модуля, класса, метода, свойства и функции. Но он не обнаруживает мои шаблоны вообще. На самом деле, если я просто уберу module.rst файл из _templates/autosummary/, он отображает весь файл точно так же, как и раньше. Я следовал за этим ТАКИМ вопросом к письму. Если вам интересно, полный репозиторий находится на GitHub.

Изменить: Кажется, он генерирует другой файл, мне пришлось удалить документы /_autosummary для него, чтобы прочитать новый шаблон. Однако теперь он генерирует файл с sparse заголовок и description заголовок. Это не входит в {% if classes %} а также {% if functions %} директивы.

Моя структура каталогов выглядит следующим образом:

  • редкий
  • документы
    • conf.py
    • index.rst
    • modules.rst
    • _templates / автореферат /module.rst

Вот соответствующие файлы на данный момент:

index.rst:

.. sparse documentation master file, created by
   sphinx-quickstart on Fri Dec 29 20:58:03 2017.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to sparse's documentation!
==================================

.. toctree::
   :maxdepth: 2
   :caption: Contents:

   modules

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

modules.rst:

API Reference
=============

Modules
-------

.. autosummary::
   :toctree: _autosummary

   sparse

_templates/autosummary/module.rst:

{{ fullname | escape | underline }}

Description
-----------

.. automodule:: {{ fullname | escape }}

{% if classes %}
Classes
-------
.. autosummary:
    :toctree: _autosummary

    {% for class in classes %}
        {{ class }}
    {% endfor %}

{% endif %}

{% if functions %}
Functions
---------
.. autosummary:
    :toctree: _autosummary

    {% for function in functions %}
        {{ function }}
    {% endfor %}

{% endif %}

1 ответ

Решение

Мне понадобились следующие файлы:

modules.rst:

API Reference
=============

.. rubric:: Modules

.. autosummary::
   :toctree: generated

   sparse

_templates/autosummary/module.rst:

{{ fullname | escape | underline }}

.. rubric:: Description

.. automodule:: {{ fullname }}

.. currentmodule:: {{ fullname }}

{% if classes %}
.. rubric:: Classes

.. autosummary::
    :toctree: .
    {% for class in classes %}
    {{ class }}
    {% endfor %}

{% endif %}

{% if functions %}
.. rubric:: Functions

.. autosummary::
    :toctree: .
    {% for function in functions %}
    {{ function }}
    {% endfor %}

{% endif %}

_templates/autosummary/class.rst:

{{ fullname | escape | underline}}

.. currentmodule:: {{ module }}

.. autoclass:: {{ objname }}

   {% block methods %}
   {% block attributes %}
   {% if attributes %}
   .. HACK -- the point here is that we don't want this to appear in the output, but the autosummary should still generate the pages.
      .. autosummary::
         :toctree:
      {% for item in all_attributes %}
         {%- if not item.startswith('_') %}
         {{ name }}.{{ item }}
         {%- endif -%}
      {%- endfor %}
   {% endif %}
   {% endblock %}

   {% if methods %}
   .. HACK -- the point here is that we don't want this to appear in the output, but the autosummary should still generate the pages.
      .. autosummary::
         :toctree:
      {% for item in all_methods %}
         {%- if not item.startswith('_') or item in ['__call__'] %}
         {{ name }}.{{ item }}
         {%- endif -%}
      {%- endfor %}
   {% endif %}
   {% endblock %}

_templates/autosummary/base.rst:

{{ fullname | escape | underline}}

.. currentmodule:: {{ module }}

.. auto{{ objtype }}:: {{ objname }}

Мне также нужно было пойти в sphinx/ext/autosummary/generate.py и установить imported_members=True в функции generate_autosummary_docs,

Если вы не используете numpydoc как и я, вам может понадобиться удалить .. HACK директивы.

Начиная с версии 3.1 Sphinx (июнь 2020 г.), вы можете использовать новый :recursive: возможность получить sphinx.ext.autosummary для автоматического обнаружения каждого модуля в вашем пакете, даже если он глубоко вложен, и автоматического создания документации для каждого атрибута, класса, функции и исключения в этом модуле.

Смотрите мой ответ здесь: /questions/2903232/avtodok-sfinksa-ne-dostatochno-avtomaticheskij/55229945#55229945

Другие вопросы по тегам