【问题标题】:Output/Print a "readable" dictionary输出/打印一个“可读”的字典
【发布时间】:2012-06-08 12:39:30
【问题描述】:

我正在准备一个 api,并使用 docstrings 作为文档。 api 服务选择相关的 ApiClass 方法并加入每个文档字符串以创建文档。这样,程序开发人员和 api 用户都可以访问相同的文档。

我的班级结构是这样的:

API_STATUS = {
    1: 'some status',
    2: 'some other status message'
}

class MyApi:
    def __init__(self):
        blah blah blah

    def ApiService1(self, some_param):
        """ 
        here is the documentation
            * some thing
            * some other thing
        keep on explanation
        """
        do some job 

    def  ApiService2(self, some_param):
        """"
        Another doc...
        """
        do some other job

我正在使用HttpResponse 返回最终的文档字符串。所以当我请求服务文档时,输出是非常可读的

ApiService1

    here is the documentation
        * some thing
        * some other thing
    keep on explanation

ApiService2

    Another doc...

到目前为止一切都很好,但是有一些变量,如API_STATUS 字典和一些列表,我希望将它们添加到文档中。但是当我将它们解析为字符串或调用repr 函数时,所有格式都消失了

{1: '一些状态' 2: '一些其他状态消息', 3: '.....', 4: '........', ....}

这使得它不可读(因为 dict 有大约 50 个元素。)。

我不想写下来作为一个文档字符串(因为在未来的更新中,相关的字典可能会被更新,而字典字符串可能会被遗忘)

有没有办法将我的字典添加到我的响应文档字符串中(在将其返回为HttpResponse 之前)而不删除样式缩进?

【问题讨论】:

    标签: python django dictionary formatting


    【解决方案1】:

    使用 pprint:

    >>> API_STATUS = {1: 'some status', 2: 'some other status message'}
    >>> import pprint
    >>> pprint.pprint(API_STATUS, width=1)
    {1: 'some status',
     2: 'some other status message'}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-22
      • 2017-05-14
      • 1970-01-01
      • 1970-01-01
      • 2015-03-02
      • 2020-07-20
      • 2018-10-12
      • 1970-01-01
      相关资源
      最近更新 更多