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

文档生成工具:

自带的pydoc,比较差

建议使用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文件是源文件,index.rst负责首页的布局。build目录为生成的目标html文件,找到index.html打开就行

692500-20190214190108528-1693226745.png

如何将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:3usecases/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”这一点,并不是那么容易达到的,我就碰到了这个问题:

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

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

编辑 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 Sphinx1.8.4quickstart utility.

Please enter valuesforthe following settings (just press Enter to

accept adefault value, if one is given inbrackets).

Selected root path: .

You have two optionsfor placing the build directory forSphinx 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 staticfiles. You can enter another prefix (suchas ".") to replace the underscore.> Name prefix for templates and staticdir [_]:

The project name will occurin several places inthe built documentation.>Project name: test>Author name(s): tester> Project release []: 1.0If the documents are to be writtenina language other than English,

you canselecta 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 suffixfor source files. Commonly, this is either ".txt"or".rst". Only files with thissuffix are considered documents.>Source file suffix [.rst]:

One documentis special in that it isconsidered the top node of the"contents tree", that is, it isthe root of the hierarchical structure

of the documents. Normally,this is "index", but if your "index"documentis a custom template, you can also set thisto 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 generatedforyou 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 builderwhere "builder" is one of the supported builders, e.g. html, latex or linkcheck.

django结合sphinx的config.py:

# -*- coding: utf-8 -*-#

# Configuration fileforthe 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) areinanother directory,

# add these directories to sys.path here. If the directoryisrelative 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'# TheshortX.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,asstrings. 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 tothisdirectory.

templates_path= ['_templates']

# The suffix(es) of source filenames.

# You can specify multiple suffixas a list of string:

#

# source_suffix= ['.rst', '.md']

source_suffix= '.rst'# The master toctree document.

master_doc= 'index'# The languageforcontent autogenerated by Sphinx. Refer to documentation

#fora list of supported languages.

#

# Thisis also used if you docontent translation via gettext catalogs.

# Usually youset "language" from the command line forthese cases.

language=None

# List of patterns, relative to source directory, that match files and

# directories to ignore when lookingforsource 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 usefor 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 availableforeach theme, see the

# documentation.

#

# html_theme_options={}

# Add any paths that contain customstatic files (such asstyle sheets) here,

# relative tothis directory. They are copied after the builtin staticfiles,

# 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.

#

# Thedefault sidebars (for documents that don't match any pattern) are

# defined by theme itself. Builtin themes are usingthese templates by

#default: ``['localtoc.html', 'relations.html', 'sourcelink.html',

#'searchbox.html']``.

#

# html_sidebars={}

#-- Options for HTMLHelp output ---------------------------------------------# Output filebase name forHTML 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 stuffforthe 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 ownclass]).

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 identificationforthe text.

#

# epub_uid= ''# A list of files that should not be packed into the epub file.

epub_exclude_files= ['search.html']

#-- Extension configuration -------------------------------------------------

sphinx中文手册: https://zh-sphinx-doc.readthedocs.io/en/latest/contents.html

英文手册:http://www.sphinx-doc.org/en/master/usage/quickstart.html#defining-document-structure

pycharm的sphinx设置:

692500-20190218230820889-260800266.png

参考:

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

2、https://cloud.tencent.com/developer/ask/83415

3、https://www.cnblogs.com/ToDoToTry/p/9361838.html

4、https://www.cnblogs.com/niejinmei/p/8918858.html

5、https://www.jianshu.com/p/d4a1347f467b

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值