python启用gzip实现压缩响应体

 更新时间:2025年05月15日 11:18:05   作者:去追风,去看海  
这篇文章主要为大家详细介绍了python后端如何启用gzip实现压缩响应体,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下

1. Flask

服务器端代码 (使用 Flask)

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 响应)

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)

pip install fastapi uvicorn fastapi-compress
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 响应)

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.")

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

相关文章

  • python中tf.boolean_mask()函数的使用方法详解

    python中tf.boolean_mask()函数的使用方法详解

    这篇文章主要介绍了python中tf.boolean_mask()函数的使用方法详解, tf.boolean_mask() 函数的作用是通过布尔值对指定的列的元素进行过滤,需要的朋友可以参考下
    2023-11-11
  • Python Tkinter GUI编程实现Frame切换

    Python Tkinter GUI编程实现Frame切换

    本文主要介绍了Python Tkinter GUI编程实现Frame切换,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-04-04
  • python如何生成textgrid文件

    python如何生成textgrid文件

    这篇文章主要介绍了python如何生成textgrid文件,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧
    2024-07-07
  • 使用Python优雅地处理带有JWT认证的接口提交

    使用Python优雅地处理带有JWT认证的接口提交

    在传统的网页爬虫开发中,我们习惯于直接请求目标 URL,解析 HTML,提取数据,然而,随着现代 Web 应用架构的演进,前后端分离(SPA)已成为主流,为了保护这些接口的安全,开发者往往会设置一道门卫JWT,所以本文给大家介绍了如何使用Python优雅地处理带有JWT认证的接口提交
    2026-01-01
  • Python通过正则表达式选取callback的方法

    Python通过正则表达式选取callback的方法

    这篇文章主要介绍了Python通过正则表达式选取callback的方法,涉及Python正则表达式及回调函数的使用技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-07-07
  • Python全自动实现Excel数据分列

    Python全自动实现Excel数据分列

    在 Excel 数据处理中,数据分列是高频刚需操作,本文将使用免费 Excel 处理库,通过 Python 实现全自动单列拆分多列,并对比 Excel 自带分列与 VBA 方案,帮你快速选出最合适的处理方式
    2026-04-04
  • Jupyter notebook无法链接内核、运行代码问题

    Jupyter notebook无法链接内核、运行代码问题

    文章主要介绍了在VSCode中使用Jupyter Notebook遇到的问题及其解决过程,问题包括包版本冲突、文件冲突、路径错误和找不到文件,通过逐一排查和安装相关依赖包,最终解决了这些问题,使得Jupyter Notebook可以在VSCode中正常运行
    2025-02-02
  • 基于Python实现对PDF文件的OCR识别

    基于Python实现对PDF文件的OCR识别

    大家可能听说过使用Python进行OCR识别操作。在Python中,最出名的库便是Google所资助的tesseract。利用tesseract可以很轻松地对图像进行识别。现在问题来了,如果想对一个PDF文档进行OCR识别,该怎么做呢?下面一起来看看。
    2016-08-08
  • Python类super()及私有属性原理解析

    Python类super()及私有属性原理解析

    这篇文章主要介绍了Python类super()及私有属性原理解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-06-06
  • 用Python实现命令行闹钟脚本实例

    用Python实现命令行闹钟脚本实例

    今天我们讲一下用Python写的一个小脚本。这是一个可以在命令行运行的闹钟脚本,对于日常大家工作很实用,有需要的朋友们可以参考借鉴。
    2016-09-09

最新评论