SoFunction
Updated on 2025-05-15

python enables gzip to implement compressed response body

1. Flask

Server-side code (using Flask)

from flask import Flask, jsonify, request
from flask_compress import Compress
import logging

app = Flask(__name__)
Compress(app)  # Enable gzip compression
#Configuration log(level=)
logger = (__name__)

@('/data', methods=['GET'])
def get_data():
    try:
        # Process request parameters        count = int(('count', 100))
        
        # Return some example JSON data        data = {
            'message': 'Hello, this is compressed data!',
            'numbers': list(range(count))
        }
        return jsonify(data)
    except Exception as e:
        (f"Error occurred: {e}")
        return jsonify({'error': 'Internal Server Error'}), 500

@(404)
def page_not_found(e):
    return jsonify({'error': 'Not Found'}), 404

if __name__ == '__main__':
    (debug=True)

Client code (receive and decompress gzip response)

import requests
import gzip
import json
from io import BytesIO

def fetch_data(url):
    try:
        # Send a request to the server        response = (url)

        # Check the response header to confirm whether the data is compressed by gzip        if ('Content-Encoding') == 'gzip':
            # Use gzip to decompress the response content            compressed_content = BytesIO()
            with (fileobj=compressed_content, mode='rb') as f:
                decompressed_data = ()
            
            # Decode the decompressed data            data = (decompressed_data.decode('utf-8'))
            return data
        else:
            return ()
    except  as e:
        print(f"HTTP request failed: {e}")
        return None
    except  as e:
        print(f"Failed to decode JSON: {e}")
        return None
    except Exception as e:
        print(f"An error occurred: {e}")
        return None

if __name__ == '__main__':
    url = 'http://127.0.0.1:5000/data?count=50'
    data = fetch_data(url)
    if data:
        print(data)
    else:
        print("Failed to fetch data.")

2. FastAPI

Server-side code (using FastAPI)

pip install fastapi uvicorn fastapi-compress
from fastapi import FastAPI, Request, HTTPException
from  import JSONResponse
from fastapi_compress import Compress
import logging

app = FastAPI()
compressor = Compress()
compressor.init_app(app)

#Configuration log(level=)
logger = (__name__)

@("/data")
async def get_data(count: int = 100):
    try:
        # Return some example JSON data        data = {
            'message': 'Hello, this is compressed data!',
            'numbers': list(range(count))
        }
        return JSONResponse(content=data)
    except Exception as e:
        (f"Error occurred: {e}")
        raise HTTPException(status_code=500, detail="Internal Server Error")

@app.exception_handler(404)
async def not_found_handler(request: Request, exc: HTTPException):
    return JSONResponse(status_code=404, content={'error': 'Not Found'})

if __name__ == '__main__':
    import uvicorn
    (app, host="127.0.0.1", port=8000, log_level="info")

Client code (receive and decompress gzip response)

import requests
import gzip
import json
from io import BytesIO

def fetch_data(url):
    try:
        # Send a request to the server        response = (url)

        # Check the response header to confirm whether the data is compressed by gzip        if ('Content-Encoding') == 'gzip':
            # Use gzip to decompress the response content            compressed_content = BytesIO()
            with (fileobj=compressed_content, mode='rb') as f:
                decompressed_data = ()
            
            # Decode the decompressed data            data = (decompressed_data.decode('utf-8'))
            return data
        else:
            return ()
    except  as e:
        print(f"HTTP request failed: {e}")
        return None
    except  as e:
        print(f"Failed to decode JSON: {e}")
        return None
    except Exception as e:
        print(f"An error occurred: {e}")
        return None

if __name__ == '__main__':
    url = 'http://127.0.0.1:8000/data?count=50'
    data = fetch_data(url)
    if data:
        print(data)
    else:
        print("Failed to fetch data.")

This is the article about enabling gzip to implement compressed response bodies in Python. For more related contents of gzip compressed response bodies in Python, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!