【问题标题】:DRF Pagination custom response without model APIView没有模型 APIView 的 DRF 分页自定义响应
【发布时间】:2021-11-25 19:31:55
【问题描述】:

您好,我在 Django 中有一个项目,它对不同的数据库执行多个查询,并在多个端点返回它们,为此我使用 Pandas 和 DRF (APIViews)。

当响应很长并且逻辑上服务器内存不足时会出现问题,我知道我需要对结果进行分页但我没有找到方法,因为我不使用模型或序列化程序,我使用 pandas 进行原始查询以进行查询。

有没有办法按照我的方式对结果进行分页?

我留下了一些我的代码的 sn-ps。

class AffiliateAPIView(APIView):
    permission_classes = (IsAuthenticated,)  
    def get(self, request):
        insurance = self.request.query_params.get('insurance', None)
        emergensys_df = pd.read_sql_query(general_attention(insurance), engine())
        return Response(emergensys_df.to_dict(orient='records'))

【问题讨论】:

  • This 可能会有所帮助

标签: django pandas django-rest-framework


【解决方案1】:

您应该实现流式响应。 Django为此提供StreamingHttpResponsehttps://docs.djangoproject.com/en/3.2/ref/request-response/#streaminghttpresponse-objects 基本上,您应该执行以下操作:

  • 创建一个生成器,它使用LIMITOFFSET SQL 运算符按块从数据库中获取数据,对其进行处理,然后按块返回。
  • 创建并返回StreamingHttpResponse 并将生成器传递给它,例如:return StreamingHttpResponse(your_generator)

【讨论】:

    猜你喜欢
    • 2018-06-12
    • 2018-05-21
    • 2017-08-26
    • 2021-11-29
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 2015-12-22
    • 2015-11-12
    相关资源
    最近更新 更多