亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

python啟用gzip實(shí)現(xiàn)壓縮響應(yīng)體

 更新時(shí)間:2025年05月15日 11:18:05   作者:去追風(fēng),去看海  
這篇文章主要為大家詳細(xì)介紹了python后端如何啟用gzip實(shí)現(xiàn)壓縮響應(yīng)體,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

1. Flask

服務(wù)器端代碼 (使用 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:
        # 處理請(qǐng)求參數(shù)
        count = int(request.args.get('count', 100))
        
        # 返回一些示例 JSON 數(shù)據(jù)
        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 響應(yīng))

import requests
import gzip
import json
from io import BytesIO

def fetch_data(url):
    try:
        # 發(fā)送請(qǐng)求到服務(wù)器端
        response = requests.get(url)

        # 檢查響應(yīng)頭,確認(rèn)數(shù)據(jù)是否被 gzip 壓縮
        if response.headers.get('Content-Encoding') == 'gzip':
            # 使用 gzip 解壓響應(yīng)內(nèi)容
            compressed_content = BytesIO(response.content)
            with gzip.GzipFile(fileobj=compressed_content, mode='rb') as f:
                decompressed_data = f.read()
            
            # 解碼解壓后的數(shù)據(jù)
            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

服務(wù)器端代碼 (使用 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 數(shù)據(jù)
        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 響應(yīng))

import requests
import gzip
import json
from io import BytesIO

def fetch_data(url):
    try:
        # 發(fā)送請(qǐng)求到服務(wù)器端
        response = requests.get(url)

        # 檢查響應(yīng)頭,確認(rèn)數(shù)據(jù)是否被 gzip 壓縮
        if response.headers.get('Content-Encoding') == 'gzip':
            # 使用 gzip 解壓響應(yīng)內(nèi)容
            compressed_content = BytesIO(response.content)
            with gzip.GzipFile(fileobj=compressed_content, mode='rb') as f:
                decompressed_data = f.read()
            
            # 解碼解壓后的數(shù)據(jù)
            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.")

到此這篇關(guān)于python啟用gzip實(shí)現(xiàn)壓縮響應(yīng)體的文章就介紹到這了,更多相關(guān)python gzip壓縮響應(yīng)體內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 解析python的局部變量和全局變量

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

    函數(shù)內(nèi)部定義的變量就叫局部變量而如果一個(gè)變量既能在一個(gè)函數(shù)中使用,也可以在其他函數(shù)中使用,這樣的變量就是全局變量。 本文給大家介紹python的局部變量和全局變量的相關(guān)知識(shí),感興趣的朋友一起看看吧
    2019-08-08
  • Node.js 和 Python之間該選擇哪個(gè)?

    Node.js 和 Python之間該選擇哪個(gè)?

    這篇文章主要介紹了Node.js 和 Python之間的優(yōu)劣,并得出結(jié)論,希望能為你在項(xiàng)目選擇哪種技術(shù)時(shí)提供一些幫助。感興趣的朋友可以了解下
    2020-08-08
  • 一個(gè)基于flask的web應(yīng)用誕生 記錄用戶賬戶登錄狀態(tài)(6)

    一個(gè)基于flask的web應(yīng)用誕生 記錄用戶賬戶登錄狀態(tài)(6)

    一個(gè)基于flask的web應(yīng)用誕生第六篇,這篇文章主要介紹了記錄用戶賬戶登錄狀態(tài)功能開(kāi)發(fā),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-04-04
  • django ajax json的實(shí)例代碼

    django ajax json的實(shí)例代碼

    今天就為大家分享一篇django ajax json的實(shí)例代碼,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-05-05
  • 解決Numpy與Pytorch彼此轉(zhuǎn)換時(shí)的坑

    解決Numpy與Pytorch彼此轉(zhuǎn)換時(shí)的坑

    這篇文章主要介紹了解決Numpy與Pytorch彼此轉(zhuǎn)換時(shí)的坑,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-05-05
  • Python利用operator模塊實(shí)現(xiàn)對(duì)象的多級(jí)排序詳解

    Python利用operator模塊實(shí)現(xiàn)對(duì)象的多級(jí)排序詳解

    python中的operator模塊提供了一系列的函數(shù)操作。下面這篇文章主要給大家介紹了在Python中利用operator模塊實(shí)現(xiàn)對(duì)象的多級(jí)排序的相關(guān)資料,需要的朋友可以參考借鑒,下面來(lái)一起看看吧。
    2017-05-05
  • Python替換NumPy數(shù)組中大于某個(gè)值的所有元素實(shí)例

    Python替換NumPy數(shù)組中大于某個(gè)值的所有元素實(shí)例

    這篇文章主要介紹了Python替換NumPy數(shù)組中大于某個(gè)值的所有元素實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-06-06
  • Python實(shí)現(xiàn)文件按照日期命名的方法

    Python實(shí)現(xiàn)文件按照日期命名的方法

    這篇文章主要介紹了Python實(shí)現(xiàn)文件按照日期命名的方法,涉及Python針對(duì)文件的遍歷、讀寫及時(shí)間操作相關(guān)技巧,需要的朋友可以參考下
    2015-07-07
  • Python離線安裝第三方庫(kù)詳細(xì)操作流程

    Python離線安裝第三方庫(kù)詳細(xì)操作流程

    在使用Python開(kāi)發(fā)過(guò)程中,我們經(jīng)常需要使用各種第三方庫(kù)來(lái)擴(kuò)展Python的功能,這篇文章主要給大家介紹了關(guān)于Python離線安裝第三方庫(kù)的相關(guān)資料,需要的朋友可以參考下
    2023-11-11
  • Python 列表反轉(zhuǎn)顯示的四種方法

    Python 列表反轉(zhuǎn)顯示的四種方法

    這篇文章主要介紹了Python 列表反轉(zhuǎn)顯示的四種方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11

最新評(píng)論