pythongzipcompresspython启用gzip实现压缩响应体

目录
  • 1. Flask
    • 服务器端代码 (使用 Flask)
    • 客户端代码 (接收并解压 gzip 响应)
  • 2. FastAPI
    • 服务器端代码 (使用 FastAPI)
    • 客户端代码 (接收并解压 gzip 响应)

1. Flask

服务器端代码 (使用 Flask)

from flask import Flask, jsonify, requestfrom flask_compress import Compressimport loggingapp = 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’}), 404if __name__ == ‘__main__’: app.run(debug=True)

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

import requestsimport gzipimport jsonfrom io import BytesIOdef 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 Noneif __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)

pip install fastapi uvicorn fastapi-compress

from fastapi import FastAPI, Request, HTTPExceptionfrom fastapi.responses import JSONResponsefrom fastapi_compress import Compressimport loggingapp = 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 响应)

import requestsimport gzipimport jsonfrom io import BytesIOdef 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 Noneif __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.”)

到此这篇关于python启用gzip实现压缩响应体的文章就介绍到这了,更多相关python gzip压缩响应体内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!

无论兄弟们可能感兴趣的文章:

  • Python实现压缩与解压gzip大文件的技巧
  • Python中使用gzip模块压缩文件的简单教程
  • Python使用Gzip解压的示例详解
  • 对Python之gzip文件读写的技巧详解
版权声明

返回顶部