python后端 启用 gzip 压缩响应体

1. Flask

服务器端代码 (使用 Flask)

python 复制代码
from flask import Flask, jsonify, request
from flask_compress import Compress
import logging

app = Flask(__name__)
Compress(app)  # 启用 gzip 压缩

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

@app.route('/data', methods=['GET'])
def get_data():
    try:
        # 处理请求参数
        count = int(request.args.get('count', 100))
        
        # 返回一些示例 JSON 数据
        data = {
            'message': 'Hello, this is compressed data!',
            'numbers': list(range(count))
        }
        return jsonify(data)
    except Exception as e:
        logger.error(f"Error occurred: {e}")
        return jsonify({'error': 'Internal Server Error'}), 500

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

if __name__ == '__main__':
    app.run(debug=True)

客户端代码 (接收并解压 gzip 响应)

python 复制代码
import requests
import gzip
import json
from io import BytesIO

def fetch_data(url):
    try:
        # 发送请求到服务器端
        response = requests.get(url)

        # 检查响应头,确认数据是否被 gzip 压缩
        if response.headers.get('Content-Encoding') == 'gzip':
            # 使用 gzip 解压响应内容
            compressed_content = BytesIO(response.content)
            with gzip.GzipFile(fileobj=compressed_content, mode='rb') as f:
                decompressed_data = f.read()
            
            # 解码解压后的数据
            data = json.loads(decompressed_data.decode('utf-8'))
            return data
        else:
            return response.json()
    except requests.RequestException as e:
        print(f"HTTP request failed: {e}")
        return None
    except json.JSONDecodeError 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

服务器端代码 (使用 FastAPI)

python 复制代码
pip install fastapi uvicorn fastapi-compress
python 复制代码
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import JSONResponse
from fastapi_compress import Compress
import logging

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

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

@app.get("/data")
async def get_data(count: int = 100):
    try:
        # 返回一些示例 JSON 数据
        data = {
            'message': 'Hello, this is compressed data!',
            'numbers': list(range(count))
        }
        return JSONResponse(content=data)
    except Exception as e:
        logger.error(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
    uvicorn.run(app, host="127.0.0.1", port=8000, log_level="info")

客户端代码 (接收并解压 gzip 响应)

python 复制代码
import requests
import gzip
import json
from io import BytesIO

def fetch_data(url):
    try:
        # 发送请求到服务器端
        response = requests.get(url)

        # 检查响应头,确认数据是否被 gzip 压缩
        if response.headers.get('Content-Encoding') == 'gzip':
            # 使用 gzip 解压响应内容
            compressed_content = BytesIO(response.content)
            with gzip.GzipFile(fileobj=compressed_content, mode='rb') as f:
                decompressed_data = f.read()
            
            # 解码解压后的数据
            data = json.loads(decompressed_data.decode('utf-8'))
            return data
        else:
            return response.json()
    except requests.RequestException as e:
        print(f"HTTP request failed: {e}")
        return None
    except json.JSONDecodeError 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.")
相关推荐
weixin_307779131 小时前
流媒体娱乐服务平台在AWS上使用Presto作为大数据的交互式查询引擎的具体流程和代码
大数据·python·音视频·aws
職場上的造物主1 小时前
高清种子资源获取指南 | ✈️@seedlinkbot
python·ios·php·音视频·视频编解码·视频
〖是♂我〗2 小时前
自定义数据集 使用scikit-learn中svm的包实现svm分类
开发语言·python
抱抱宝2 小时前
Pyecharts之特殊图表的独特展示
python·信息可视化·数据分析
deephub3 小时前
Python GIL(全局解释器锁)机制对多线程性能影响的深度分析
python·机器学习·gil
MatpyMaster4 小时前
基于PyQt5打造的实用工具——PDF文件加图片水印,可调大小位置,可批量处理!
python·pdf
go54631584654 小时前
python 从知网的期刊导航页面抓取与农业科技相关的数据
开发语言·python·科技
米码收割机5 小时前
【python】tkinter实现音乐播放器(源码+音频文件)【独一无二】
开发语言·python·pygame
星如雨グッ!(๑•̀ㅂ•́)و✧5 小时前
Java NIO全面详解
java·python·nio
笛柳戏初雪5 小时前
Python中的函数(下)
开发语言·python