使用sphinx自动建立API文档(二)定制化

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/longgb123/article/details/81841320

1、网站主题修改

上面生成的网页风格比较像flask的主页,实际上使用就是同一主题alabaster
修改conf.py文件:html_theme = 'alabaster'
将值修改为喜欢的风格,sphinxdoc的风格是matplotlib的主题样式;naturepandas的主题,
个人比较喜欢nature,将上面修改为:

html_theme = 'nature'

重新运行

sphinx-apidoc -o ./source ../src/
make clean
make html

生成文档:
image.png

2、函数分页

上面运行完后,会发现,class Demo1、Demo1_ch 都在一页中,如下:

image.png

这样会有一些问题存在,当函数较多的时候,一页中会很长,难以看清(如老版 matplotlib 的 API 页面)。
这里需要用到一个扩展:automodapi
(主页:https://sphinx-automodapi.readthedocs.io/en/latest/automodapi.html#module-sphinx_automodapi.automodapi
使用pip安装后。
修改conf.py,添加sphinx_automodapi.automodapi

image.png

source.rst文件中的automodule均替换为automodapi
demo2.rst

demo2 module
============
.. automodule:: demo2
    :members:
    :undoc-members:
    :show-inheritance:

改为

demo2 module
============
.. automodapi:: demo2
    :members:
    :undoc-members:
    :show-inheritance:

如果嫌麻烦,可以写一个自动替换的脚本replace_api.py

import os
source_api_path = 'source'
automo_method = 'automodapi' # automodapi | automodsumm | automodule
for rst_file in os.listdir(source_api_path):
    if rst_file.endswith('.rst'):
        with open(source_api_path + os.sep + rst_file, 'r') as f:
            contents = f.read()
        contents = contents.replace('automodule', automo_method)
        with open(source_api_path + os.sep + rst_file, 'w') as f:
            f.write(contents)

replace_api.py放于doc目录下,运行替换。重新运行建立 html 文件。

image.png

image.png

此时,可以看到,每个函数、类都有一个单独的页面。

3、注释方法

这里以demo2_func_ch为例:
(1)在注释中需要空一行:

image.png

才能显示出下面的参数列表和返回值列表。

image.png

(2)添加类型在变量名前:

image.png

页面也会显示类型。

image.png

(3)写例子:

image.png

上面的例子是从 pandas 里面随便粘贴的,效果如下:

image.png

(4)修改主页:
主页很空旷:

image.png

找到doc/source/index.rst文件:
修改添加,如下信息:

image.png

生成

image.png

(5)其他
sphinx 还有其他的拓展,如静态文件,样式、js 等等。功能很强大。
http://www.sphinx-doc.org/en/master/templating.html

猜你喜欢

转载自blog.csdn.net/longgb123/article/details/81841320