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)

    @after_this_request
    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 response

你可能感兴趣的:(flask,python,后端,开发语言)