由于似乎没有任何现有的解决方案,我实现了一个非常简单的 HTTP 域,我可以使用它来标记 API 方法:
import re
from docutils import nodes
from sphinx import addnodes
from sphinx.locale import l_, _
from sphinx.domains import Domain, ObjType
from sphinx.directives import ObjectDescription
http_method_sig_re = re.compile(r'^(GET|POST|PUT|DELETE)?\s?(\S+)(.*)$')
class HTTPMethod(ObjectDescription):
def handle_signature(self, sig, signode):
m = http_method_sig_re.match(sig)
if m is None:
raise ValueError
verb, url, query = m.groups()
if verb is None:
verb = 'GET'
signode += addnodes.desc_addname(verb, verb)
signode += addnodes.desc_name(url, url)
if query:
params = query.strip().split()
for param in params:
signode += addnodes.desc_optional(param, param)
return url
class HTTPDomain(Domain):
"""HTTP language domain."""
name = 'http'
label = 'HTTP'
object_types = {
'method': ObjType(l_('method'), 'method')
}
directives = {
'method': HTTPMethod
}
def setup(app):
app.add_domain(HTTPDomain)
它允许我标记这样的方法,并且它们的样式在视觉上会很好:
.. http:method:: GET /api/foo/bar/:id/:slug
:param id: An id
:param slug: A slug
Retrieve list of foobars matching given id.
这是我第一次涉足 Sphinx 和 Python,所以这应该被认为是非常基本的代码。如果有人有兴趣充实这一点,请在 Github 上 fork 这个项目!