使用Sphinx autodoc记录Flask应用程序

时间:2017-06-22 10:26:13

标签: python-2.7 flask python-sphinx

我在使用Sphinx为Flask应用程序生成文档时遇到问题。没有进入应用程序的具体细节,其基本结构如下所示。

__all__ = ['APP']

<python 2 imports>

<flask imports>

<custom imports>

APP = None # module-level variable to store the Flask app

<other module level variables>

# App initialisation
def init():
    global APP

    APP = Flask(__name__)

    <other initialisation code>

try:
    init()
except Exception as e:
    logger.exception(str(e))

@APP.route(os.path.join(<service base url>, <request action>), methods=["POST"])
<request action handler>

if __name__ == '__main__':
    init()
    APP.run(debug=True, host='0.0.0.0', port=5000)

我已经在一个venv中安装了Sphinx以及Web服务所需的其他软件包,而build文件夹位于docs子文件夹中,如下所示

docs
├── Makefile
├── _build
├── _static
├── _templates
├── conf.py
├── index.rst
├── introduction.rst
└── make.bat

conf.py是通过运行sphinx-quickstart生成的,它包含行

autodoc_mock_imports = [<external imports to ignore>]

确保Sphinx将忽略列出的外部导入。 index.rst是标准的

.. myapp documentation master file, created by
   sphinx-quickstart on Fri Jun 16 12:35:40 2017.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to myapp's documentation!
=============================================

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

   introduction

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

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

我添加了introduction.rst页面来记录应用成员

===================
`myapp`
===================

Oasis Flask app that handles keys requests.

myapp.app
---------------------

.. automodule:: myapp.app
   :members:
   :undoc-members:

当我在make html中运行docs时,我在_build子文件夹中获取HTML输出,但我收到以下警告

WARNING: /path/to/myapp/docs/introduction.rst:10: (WARNING/2) autodoc: failed to import module u'myapp.app'; the following exception was raised:
Traceback (most recent call last):
  File "/path/to/myapp/venv/lib/python2.7/site-packages/sphinx/ext/autodoc.py", line 657, in import_object
__import__(self.modname)
  File "/path/to/myapp/__init__.py", line 4, in <module>
from .app import APP
  File "/path/to/myapp/app.py", line 139, in <module>
@APP.route(os.path.join(<service base url>, <request action>), methods=['GET'])
  File "/path/to/myapp/venv/lib/python2.7/posixpath.py", line 70, in join
elif path == '' or path.endswith('/'):
AttributeError: 'NoneType' object has no attribute 'endswith'

并且我没有看到我期望为应用程序成员看到的文档,例如请求处理程序和app init方法。

我不知道问题是什么,任何帮助都会受到赞赏。

1 个答案:

答案 0 :(得分:0)

尝试使用sphinx-apidoc自动生成Sphinx源,使用autodoc extension,以其他自动API文档工具的方式记录整个包。您还需要将'sphinx.ext.autodoc'添加到conf.py的Sphinx扩展程序列表中。