最近需要将API中的doc生成html给前端工程师参考调用。

于是粗率的学习了下sphinx

Sphinx 是用 Python 编写的,并且最初是为 Python 语言文档而创建,但它并不一定是以语言为中心,在某些情况下,甚至不是以程序员为中心。Sphinx 有许多用处,比如可以用它来编写整本书!

要求

安装: pip install sphinx

语法

Sphinx 使用 reStructuredText 标记语法类似与Markdown

具体可查看: http://zh-sphinx-doc.readthedocs.org/en/latest/rest.html

实战

  • 项目结构

# tree -L 1 .

├── bin
├── etc
├── ops
├── setup.py
└── example


  • 建立docs目录

# tree -L 1 .
# mkdir docs

├── bin
├── docs
├── etc
├── ops
├── setup.py
└── example


  • 根据py代码生成rst风格文件,这里我只生成ops/api/contrib下面的py文档

# sphinx-apidoc -F -o docs/ ops/api/contrib
Creating file doc/contrib.rst.
Creating file docs/conf.py.
Creating file docs/index.rst.
Creating file docs/Makefile.
Creating file docs/make.bat.

sphinx-apidoc具体用法参考: http://zh-sphinx-doc.readthedocs.org/en/latest/invocation.html#sphinx-apidoc


  • 安装readthedocs主题

# pip install sphinx_rtd_theme

编辑conf.py

import sphinx_rtd_theme
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]

在下一步生成html时,会尝试将你的项目导入并运行,因此需要将你的项目添加至python的环境变量中 编辑conf.py

os.path.append(os.path.join([os.getcwd(), "../ops/api"]))

  • 根据生成的rst文件生成html

# cd docs
# mkdir html
# sphinx-build . html

sphinx-build具体用户参考: http://zh-sphinx-doc.readthedocs.org/en/latest/invocation.html


  • 自定义生成文档的类或方法

Domain.py源代码:

class domains(tornado.web.RequestHandler):
    def get(self):
        """
        根据提交的参数类型, 返回匹配到的记录列表
 
        如果没有提交任何参数, 返回所有的域名列表
 
        ip
            合法的ipv4或ipv6的值, 返回解析是此IP的记录列表
 
        domain
            完整的域名格式(记录 + 域名), 返回此域名下的所有解析列表
 
        domain_id
            返回此域名id下的所有记录列表
 
        CLI Example::
 
            curl -X GET http://URL/domain?ip=1.1.1.1
 
        返回参考:
            * JSON::
 
                [
                    {
                        "id":"16894439",
                        "name":"@",
                        "line":"\u9ed8\u8ba4",
                        "type":"A",
                        "ttl":"600",
                        "value":"1.1.1.1",
                        "mx":"0",
                        "enabled":"1",
                        "status":"enabled",
                        "monitor_status":"",
                        "remark":"",
                        "updated_on":"2012-11-23 22:17:47"
                    },
                ]
        """
        self.write("hello")

生成domains类中get, post, put, delete方法

编辑contrib.rst

contrib.Domain module
-------------------
 
.. automodule:: contrib.Domain       从contrib.Domain中生成文档
    :undoc-members:       如果没有文档就不显示
 
    .. autoclass:: domains     指定只生成domains类中的文档
        :members: get, post, put, delete       指定只生成这几个方法的文档

效果

sphinx