使用 sphinx 製作簡潔而又美觀的文檔

最近需要將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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章