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:
# 處理請求參數(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ā)送請求到服務(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ā)送請求到服務(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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
一個(gè)基于flask的web應(yīng)用誕生 記錄用戶賬戶登錄狀態(tài)(6)
一個(gè)基于flask的web應(yīng)用誕生第六篇,這篇文章主要介紹了記錄用戶賬戶登錄狀態(tài)功能開發(fā),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-04-04
解決Numpy與Pytorch彼此轉(zhuǎn)換時(shí)的坑
這篇文章主要介紹了解決Numpy與Pytorch彼此轉(zhuǎn)換時(shí)的坑,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05
Python利用operator模塊實(shí)現(xiàn)對象的多級排序詳解
python中的operator模塊提供了一系列的函數(shù)操作。下面這篇文章主要給大家介紹了在Python中利用operator模塊實(shí)現(xiàn)對象的多級排序的相關(guān)資料,需要的朋友可以參考借鑒,下面來一起看看吧。2017-05-05
Python替換NumPy數(shù)組中大于某個(gè)值的所有元素實(shí)例
這篇文章主要介紹了Python替換NumPy數(shù)組中大于某個(gè)值的所有元素實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
Python實(shí)現(xiàn)文件按照日期命名的方法
這篇文章主要介紹了Python實(shí)現(xiàn)文件按照日期命名的方法,涉及Python針對文件的遍歷、讀寫及時(shí)間操作相關(guān)技巧,需要的朋友可以參考下2015-07-07

