Henry
发布于 2025-06-16 / 2 阅读
0
0

Python - 添加 Sphinx 注释并生成注释文档

背景简介

使用Python编写Sphinx注释,自动生成专业API文档,提升代码可读性与维护性,简洁高效。

环境信息

  1. Python 3.12.9 

详细步骤

**补充信息:**项目结构

MyProject
  \modules
    \common.py
  \source
    \index.rst

第一步: 安装 Sphinx 

$ pip install sphinx

第二步: 在 Python 代码中添加 Sphinx 可读格式备注

# modules/common.py
from flask import Blueprint, jsonify
from models.chatbot_model import Chatbot

common_blueprint = Blueprint('common', __name__)

chatbot_instance = Chatbot()

@chat_blueprint.route('/common/healthy', methods=['get'])
def healthcheck():
    """
    Endpoint to check the health of the server.

    GET Args:
    None

    Returns:
    dict: A JSON object representing the server's health status.
    Example:{"status": "healthy"}
    """
    # Additional health check logic can be added here
    return jsonify({"status": "healthy"}), 200

第三步: 更新 Sphinx 配置文件

  • 添加 source/modules_common.rst 配置模块信息
common modules
==================
.. automodule:: modules.common
 :members:
 :undoc-members:
 :show-inheritance:
  • 修改 source/index.rst,添加 modules_commmon (跟前面创建的文件名相同)
.. Chat Robot Backend documentation master file, created by
   sphinx-quickstart on Wed Mar 12 17:26:42 2025.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Chat Robot Backend documentation
================================

Add your content using ``reStructuredText`` syntax. See the
`reStructuredText <https://www.sphinx-doc.org/en/master/usage/restructuredtext/index.html>`_
documentation for details.


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

   redis_service
   db_service
   models_user_model
   models_chatbot_model
   modules_chatbot
   modules_commmon
  • 更新 source/conf.py
    • sys.path.insert(0, os.path.abspath('..')) 添加项目路径
    • 更新 extensions  部分,添加'sphinx.ext.autodoc'
import os
import sys

sys.path.insert(0, os.path.abspath('..'))

# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information

project = 'Chat Robot Backend'
copyright = '2025, Henry Lin'
author = 'Henry Lin'
release = '1.0.0'

# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration

extensions = [
    'sphinx.ext.autodoc',
    # ... 其他扩展
]


templates_path = ['_templates']
exclude_patterns = []


# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output

html_theme = "nature"
html_static_path = ['_static']

第四步: 生成 html

$ make html
正在运行 Sphinx v8.2.3
正在加载翻译 [en]…完成
正在加载 Pickle 序列化的环境... 完成
正在构建 [mo]: 0 个 po 文件的目标文件已过期
正在写入输出……
正在构建 [html]: 0 个源文件的目标文件已过期
正在更新环境:有 0 个新增文件,有 1 个文件已被修改,有 0 个文件已被移除
正在读取源文件……[100%] modules_common
正在查找当前已过期的文件……没有找到已过期文件
正在 Pickle 序列化环境... 完成
正在校验一致性... 完成
正在准备写入文档... 完成
正在复制资产文件... 
正在复制静态文件... 
Writing evaluated template result to /home/myserver/ChatRobot/ChatRobotBackend/build/html/_static/language_data.js
Writing evaluated template result to /home/myserver/ChatRobot/ChatRobotBackend/build/html/_static/documentation_options.js
Writing evaluated template result to /home/myserver/ChatRobot/ChatRobotBackend/build/html/_static/basic.css
Writing evaluated template result to /home/myserver/ChatRobot/ChatRobotBackend/build/html/_static/nature.css
正在复制静态文件: 完成
正在复制额外文件... 
正在复制额外文件: 完成
正在复制资产文件: 完成
正在写入输出……[100%] modules_common
正在生成索引... genindex py-modindex 完成
正在写入附加页面... search 完成
正在导出 English (code: en) 的搜索索引... 完成
正在导出对象清单... 完成
build succeeded.

HTML 页面保存在 build/html 目录。

第五步: 进入 build/html 目录查看页面


以上便是本文的全部内容,感谢您的阅读,如遇到任何问题,欢迎在评论区留言讨论。



评论