flask response 返回压缩

import gzip
from io import BytesIO
from flask import jsonify, after_this_request, request

@app.get("/book")
def get_book():
    """
    to get all books
    """
    data = {
        "code": 0,
        "message": "ok",
        "data": [
            {"bid": 1, "age": 12, "author": 22222},
            {"bid": 2, "age": 13, "author": 11111}
        ]
    }

    response = jsonify(data)

    def compress(response):
        if 'gzip' in request.headers.get('Accept-Encoding', ''):
            compressed_data = BytesIO()

            with gzip.GzipFile(fileobj=compressed_data, mode='w') as gz:
                gz.write(response.data)

            response.data = compressed_data.getvalue()
            response.headers['Content-Encoding'] = 'gzip'
            response.headers['Content-Length'] = len(response.data)

        return response

    return compress(response)
posted @ 2023-06-19 10:24  一枚码农  阅读(157)  评论(0编辑  收藏  举报