关于django-rest-framework:drfyasg打开文档速度很慢的解决方案
背景在应用drf-yasg的时候,有时候一不小心写了一些代码,比方写serializers的时候写了一些default参数,该参数是会查询数据库的,关上swagger文档的时候就会触发数据库查问,从而缓缓的减少了关上swagger文档的工夫 找到耗时的接口须要装置依赖pip install prettytable不便打印耗时接口 在我的项目根目录下新增一个drf-yasg的generator 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,依照耗时倒序排列 ...