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的局部变量和全局变量

    解析python的局部变量和全局变量

    函数内部定义的变量就叫局部变量而如果一个变量既能在一个函数中使用,也可以在其他函数中使用,这样的变量就是全局变量。 本文给大家介绍python的局部变量和全局变量的相关知识,感兴趣的朋友一起看看吧
    2019-08-08
  • Node.js 和 Python之间该选择哪个?

    Node.js 和 Python之间该选择哪个?

    这篇文章主要介绍了Node.js 和 Python之间的优劣,并得出结论,希望能为你在项目选择哪种技术时提供一些帮助。感兴趣的朋友可以了解下
    2020-08-08
  • 一个基于flask的web应用诞生 记录用户账户登录状态(6)

    一个基于flask的web应用诞生 记录用户账户登录状态(6)

    一个基于flask的web应用诞生第六篇,这篇文章主要介绍了记录用户账户登录状态功能开发,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-04-04
  • django ajax json的实例代码

    django ajax json的实例代码

    今天就为大家分享一篇django ajax json的实例代码,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-05-05
  • 解决Numpy与Pytorch彼此转换时的坑

    解决Numpy与Pytorch彼此转换时的坑

    这篇文章主要介绍了解决Numpy与Pytorch彼此转换时的坑,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-05-05
  • Python利用operator模块实现对象的多级排序详解

    Python利用operator模块实现对象的多级排序详解

    python中的operator模块提供了一系列的函数操作。下面这篇文章主要给大家介绍了在Python中利用operator模块实现对象的多级排序的相关资料,需要的朋友可以参考借鉴,下面来一起看看吧。
    2017-05-05
  • Python替换NumPy数组中大于某个值的所有元素实例

    Python替换NumPy数组中大于某个值的所有元素实例

    这篇文章主要介绍了Python替换NumPy数组中大于某个值的所有元素实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-06-06
  • Python实现文件按照日期命名的方法

    Python实现文件按照日期命名的方法

    这篇文章主要介绍了Python实现文件按照日期命名的方法,涉及Python针对文件的遍历、读写及时间操作相关技巧,需要的朋友可以参考下
    2015-07-07
  • Python离线安装第三方库详细操作流程

    Python离线安装第三方库详细操作流程

    在使用Python开发过程中,我们经常需要使用各种第三方库来扩展Python的功能,这篇文章主要给大家介绍了关于Python离线安装第三方库的相关资料,需要的朋友可以参考下
    2023-11-11
  • Python 列表反转显示的四种方法

    Python 列表反转显示的四种方法

    这篇文章主要介绍了Python 列表反转显示的四种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-11-11

最新评论