发布于 2015-09-13 08:06:47 | 215 次阅读 | 评论: 0 | 来源: PHPERZ

生成文档(Generating Documentation)

公开发布API时提供相应的API使用文档。写文档本来就很沉闷繁琐,更改代码后再同步更新文档就更是如此。

幸运地是,Piston为此已经做了很多工作,使得我们可以方便地书写文档。

piston.doc 库提供了一组方法,方便我们使用Django的Views和Template生成文档。

generate_doc 函式返回一个 HandlerDocumentation 实例,该实例有下列几个方法:

* .model (get_model) 返回该handler的名称。
* .doc (get_doc) 返回给定的handler的docstring。
* .get_methods 返回一组可用的方法列表。该方法接收一个可选的关键字参数 ``include_defaults`` (默认为False),在参数为True且并没有重写默认方法的情况下,该方法的返回列表会包含默认方法。我们想使用默认方法并想将其包含在文档中时,该参数就能派上用场。

get_methods 包含一系列有趣的 HandlerMethod

  • .signature (get_signature) 返回 //signature// 方法, 前两个固定参数是Piston自动指定的 ‘self’ 和 ‘request’ 。客户端无须指定这两个参数,所以不必关心。还有一个可选的关键字参数 parse_optional (默认为 True),用来将默认为None的关键字参数转变成 “<optional>” 。
  • .doc (get_doc) 返回某个动作的docstring,所以我们应该保证handler/action都有详细的文档描述。
  • .iter_args() 会返回一个结构为(参数名,默认参数值/None)的二元组。如果默认参数值也是None,该参数值会被转换成字符串’None’。这样做是为了避免和None相混淆.因此我们就能区分返回的默认参数值终究是None还是空。

例子:

#!python

from piston.handler import BaseHandler
from piston.doc import generate_doc

class BlogpostHandler(BaseHandler):
    model = Blogpost

    def read(self, request, post_slug=None):
        """
        Reads all blogposts, or a specific blogpost if
        `post_slug` is supplied.
        """
        ...

    @staticmethod
    def resource_uri():
        return ('api_blogpost_handler', ['id'])

doc = generate_doc(BlogpostHandler)

print doc.name # -> 'BlogpostHandler'
print doc.model # -> <class 'Blogpost'>
print doc.resource_uri_template # -> '/api/post/{id}'

methods = doc.get_methods()

for method in methods:
    print method.name # -> 'read'
    print method.signature # -> 'read(post_slug=<optional>)'

    sig = ''

    for argn, argdef in method.iter_args():
        sig += argn

        if argdef:
            sig += "=%s" % argdef

        sig += ', '

    sig = sig.rstrip(",")

print sig # -> 'read(repo_slug=None)'

资源URL(Resource URIs)

每个资源都可以对应一个URI。调用资源的 .resource_uri() 方法就可以在Handler中访问该资源。

详见 [[FAQ#what-is-a-uri-template|FAQ: What is a URI Template]].

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务