python文档生成工具:pydoc、sphinx;django如何使用sphinx?

安装:

pip install sphinx

安装主题:

由各种主题,我选择常用的sphinx_rtd_theme

pip install sphinx_rtd_theme

使用方法:

1、创建文件夹doc:mkdir doc;cd doc;执行sphinx-quickstart,进入引导,根据需要选择yes或者no

2、执行sphinx-quickstart引导程序只会生成一个index.rst

3、在doc目录下执行sphinx-apidoc -o source  file_directory,其中file_directory是指你需要文档化的目录,这样如果有多个模块,就会生成多个.rst文件

4、在doc目录下执行make html,就会生成html文档,打开html文档,就可以了

sphinx文档介绍

django项目的目录结构,doc是用来文档化的目录,里面包含自动生成的目录build、source、source/_static、source/_templates,文件config.py、make.bat、Makefile。其他目录或者文件是make html报错时,为解决问题添加的或者是make html生成的文件。

其中config.py是配置文件。source目录下的.rst文件是源文件。build目录为生成的目标html文件,找到index.html打开就行

如何将Sphinx生成的html文档集成进入Django:

https://www.cnblogs.com/flowjacky/p/6251177.html

使用sphinx-quickstart只会生成index.dst,需哟啊使用api

make html会提示错误,根据提示进行修改

-------------------------------------------------------------

以下内容来自:http://www.huangwenchao.com.cn/2015/12/djangp-sphinx.html

安装 Sphinx 并且生成文档项目

首先我们假设已经有了一个 django 项目的架构:

myproject/
  myproject/
    __init__.py
    settings.py
    urls.py
    wsgi.py
  myapp/
    migrations/
    __init__.py
    admin.py
    models.py
    tests.py
    views.py

在这个基础上,我们要在里面加一个 docs 文件夹放文档项目:

pip3 install Sphinx
mkdir docs
cd docs
sphinx-quickstart

# 注意 autodoc 的地方一定要选是,其他选默认没什么问题。
# ...

# 最后直接生成一下:
make html

如上,先安装 Sphinx 库,然后创建一个目录,在里面执行 sphinx-quickstart,填写参数之后就可以产生文档项目的内容。

这个时候,我们应该获得一个这样的目录:

myproject/
  myproject/
  myapp/
  docs/
    _build/
      doctrees/
      html/
    _static/
    _templates/
    conf.py
    index.rst
    Makefile

很好,我们现在通过 myproject/docs/_build/html/ 就已经获得一个生成好的文档静态网站了,将这个目录静态部署,就已经搭好基本的文档项目了。

撰写基本的手工文档

具体的 reStructuredText 语法,在这里就不多说了,本人其实将这篇文档翻译了一遍,不过还是自行参考原文吧:

然后,我们只需要在项目文档里面创建文件结构以及 *.rst 文档源文件,进行编辑即可。

比较关键的就是在文档中搭建目录引用关系,最终这些目录树会将所有文档的章节拼接成一个整体的目录树:

例如我们在 docs/index.rst 里面加入这个目录树定义:

.. toctree::
   :maxdepth: 3

   usecases/index
   myapp/models
   myapp/admin
   myapp/views

这样的话,对应会目录到下面路径的这几个文件:

myproject/
  docs/
    usecases/
      index.rst
    myapp/
      admin.rst
      models.rst
      views.rst

注意,在我们计划中,usecases 用来存放纯手写的用例文档,而 myapp 文件夹里面的内容是要打算在代码中直接抽取的。

如何实现这一点?自动抽取代码呢?

绑定 Django 项目并从项目生成代码

首先,我们需要让文档项目的上下文能正确加载 django,就好像我们调用 python manage.py shell 得到的上下文一样。

然后,我们在文档里面就可以通过这样的 reST 指令块来指定抽取,以 myapp.model.rst 为例:

myapp.models module
===================

.. automodule:: myapp.models
   :members:
   :undoc-members:
   :show-inheritance:

只要指定了这个 ..automodule 指令,再 make 就可以实现抽取。

但是,我们前面的这个前提“需要让文档项目的上下文能正确加载 django”这一点,并不是那么容易达到的,我就碰到了这个问题:

Stackoverflow: Sphinx-apidoc on django build html failure on django.core.exceptions.AppRegistryNotReady

最终发现了需要在外部装载 django 上下文的方法,参见:

https://docs.djangoproject.com/en/1.9/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage

也就是说,在这里的解决办法是:

编辑 myproject/docs/conf.py,找到:

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

附近这段,然后编辑成这几行:

import django  # 这个最好可以加载顶部和其他的 import 放在一起

# 这个注意由于 django 根目录位于 `docs/conf.py` 本身的上一级目录,因此要用父目录
sys.path.insert(0, os.path.abspath('..'))  

# 下面将 settings 加到环境变量里面,等一下启动的时候就会是用这个配置
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'

# 关键,用这句加载模块和上下文
django.setup()

有了这一套,就不会出现 django.core.exceptions.AppRegistryNotReady 的异常了。

------------------------------------------------------------- 

 

sphinx-quickstart 引导过程:

➜  html sphinx-quickstart
Welcome to the Sphinx 1.8.4 quickstart utility.

Please enter values for the following settings (just press Enter to
accept a default value, if one is given in brackets).

Selected root path: .

You have two options for placing the build directory for Sphinx output.
Either, you use a directory "_build" within the root path, or you separate
"source" and "build" directories within the root path.
> Separate source and build directories (y/n) [n]: y

Inside the root directory, two more directories will be created; "_templates"
for custom HTML templates and "_static" for custom stylesheets and other static
files. You can enter another prefix (such as ".") to replace the underscore.
> Name prefix for templates and static dir [_]:

The project name will occur in several places in the built documentation.
> Project name: test
> Author name(s): tester
> Project release []: 1.0

If the documents are to be written in a language other than English,
you can select a language here by its language code. Sphinx will then
translate text that it generates into that language.

For a list of supported codes, see
http://sphinx-doc.org/config.html#confval-language.
> Project language [en]: zh_cn

The file name suffix for source files. Commonly, this is either ".txt"
or ".rst".  Only files with this suffix are considered documents.
> Source file suffix [.rst]:

One document is special in that it is considered the top node of the
"contents tree", that is, it is the root of the hierarchical structure
of the documents. Normally, this is "index", but if your "index"
document is a custom template, you can also set this to another filename.
> Name of your master document (without suffix) [index]:
Indicate which of the following Sphinx extensions should be enabled:
> autodoc: automatically insert docstrings from modules (y/n) [n]: y
> doctest: automatically test code snippets in doctest blocks (y/n) [n]:
> intersphinx: link between Sphinx documentation of different projects (y/n) [n]:
> todo: write "todo" entries that can be shown or hidden on build (y/n) [n]:
> coverage: checks for documentation coverage (y/n) [n]:
> imgmath: include math, rendered as PNG or SVG images (y/n) [n]:
> mathjax: include math, rendered in the browser by MathJax (y/n) [n]:
> ifconfig: conditional inclusion of content based on config values (y/n) [n]:
> viewcode: include links to the source code of documented Python objects (y/n) [n]: y
> githubpages: create .nojekyll file to publish the document on GitHub pages (y/n) [n]:

A Makefile and a Windows command file can be generated for you so that you
only have to run e.g. `make html' instead of invoking sphinx-build
directly.
> Create Makefile? (y/n) [y]:
> Create Windows command file? (y/n) [y]:

Creating file ./source/conf.py.
Creating file ./source/index.rst.
Creating file ./Makefile.
Creating file ./make.bat.

Finished: An initial directory structure has been created.

You should now populate your master file ./source/index.rst and create other documentation
source files. Use the Makefile to build the docs, like so:
   make builder
where "builder" is one of the supported builders, e.g. html, latex or linkcheck.

django结合sphinx的config.py:

# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import sphinx_rtd_theme
import django
import os
import sys
sys.path.insert(0, os.path.abspath('./../../../erebus_app'))

os.environ['DJANGO_SETTINGS_MODULE'] = 'erebus.settings'

django.setup()
# -- Project information -----------------------------------------------------

project = 'erebus_doc'
copyright = '2019, deluopu'
author = 'deluopu'

# The short X.Y version
version = ''
# The full version, including alpha/beta/rc tags
release = '1.0'


# -- General configuration ---------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
# 根据引导程序的选择的扩展 extensions
= [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = [] # The name of the Pygments (syntax highlighting) style to use. pygments_style = None # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # 选择模板主题 # html_theme = 'alabaster' html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # The default sidebars (for documents that don't match any pattern) are # defined by theme itself. Builtin themes are using these templates by # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', # 'searchbox.html']``. # # html_sidebars = {} # -- Options for HTMLHelp output --------------------------------------------- # Output file base name for HTML help builder. htmlhelp_basename = 'erebus_docdoc' # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'erebus_doc.tex', 'erebus\\_doc Documentation', 'deluopu', 'manual'), ] # -- Options for manual page output ------------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'erebus_doc', 'erebus_doc Documentation', [author], 1) ] # -- Options for Texinfo output ---------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'erebus_doc', 'erebus_doc Documentation', author, 'erebus_doc', 'One line description of project.', 'Miscellaneous'), ] # -- Options for Epub output ------------------------------------------------- # Bibliographic Dublin Core info. epub_title = project # The unique identifier of the text. This can be a ISBN number # or the project homepage. # # epub_identifier = '' # A unique identification for the text. # # epub_uid = '' # A list of files that should not be packed into the epub file. epub_exclude_files = ['search.html'] # -- Extension configuration -------------------------------------------------

参考:

1、http://www.huangwenchao.com.cn/2015/12/djangp-sphinx.html

猜你喜欢

转载自www.cnblogs.com/shengulong/p/10376437.html