背景

在应用drf-yasg的时候,有时候一不小心写了一些代码,比方写serializers的时候写了一些default参数,该参数是会查询数据库的,关上swagger文档的时候就会触发数据库查问,从而缓缓的减少了关上swagger文档的工夫

找到耗时的接口

须要装置依赖pip install prettytable不便打印耗时接口

在我的项目根目录下新增一个drf-yasggenerator

generators.py

import timeimport prettytablefrom drf_yasg.generators import OpenAPISchemaGeneratorclass TimeCostSchemaGenerator(OpenAPISchemaGenerator):    def __init__(self, *args, **kwargs):        super().__init__(*args, **kwargs)        self.path_method_cost_map = {}        self.table = prettytable.PrettyTable(field_names=['cost', 'method', 'url'])    def get_operation(self, view, path, prefix, method, components, request):        """计算获取每个接口的schema的工夫        如果接口操作的耗时小于0.01秒,则不记录该接口        """        now = time.perf_counter()        operation = super().get_operation(view, path, prefix, method, components, request)        cost = round(time.perf_counter() - now, 2)        if cost:            self.path_method_cost_map[(path, method)] = cost        return operation    def get_schema(self, request=None, public=False):        """在获取schema的时候打印记录下来的接口和耗时表格"""        schema = super().get_schema(request, public)        path_method_cost_items = sorted(self.path_method_cost_map.items(), key=lambda i: i[1], reverse=True)        for ((path, method), cost) in path_method_cost_items:            self.table.add_row([cost, method, path])        print(self.table)        return schema

执行命令验证

$ python manage.py generate_swagger test.json -g generators.TimeCostSchemaGenerator -o

上述命令会打印出如下格局的输入,表格三列示意接口耗时,申请办法,申请url,依照耗时倒序排列

+-------+--------+---------------------------------------------------------------+|  cost | method |                              url                              |+-------+--------+---------------------------------------------------------------+| 15.36 |  GET   |                /api/v2/**/                                    ||  3.57 |  GET   |               /api/***                                        |+-------+--------+---------------------------------------------------------------+

参数解释

  • generate_swaggerdrf-yasg自定义的命令,装置完drf-yasg之后能够间接应用
  • test.json是生成schema文件的门路
  • -g generators.TimeCostSchemaGenerator示意指定自定义generator的门路地位,程序执行的时候会依照指定参数导入
  • -o示意会笼罩旧的schema文件