python啟用gzip實(shí)現(xiàn)壓縮響應(yīng)體
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)文章
python中tf.boolean_mask()函數(shù)的使用方法詳解
這篇文章主要介紹了python中tf.boolean_mask()函數(shù)的使用方法詳解,?tf.boolean_mask()?函數(shù)的作用是通過布爾值對指定的列的元素進(jìn)行過濾,需要的朋友可以參考下2023-11-11
Python Tkinter GUI編程實(shí)現(xiàn)Frame切換
本文主要介紹了Python Tkinter GUI編程實(shí)現(xiàn)Frame切換,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04
使用Python優(yōu)雅地處理帶有JWT認(rèn)證的接口提交
在傳統(tǒng)的網(wǎng)頁爬蟲開發(fā)中,我們習(xí)慣于直接請求目標(biāo) URL,解析 HTML,提取數(shù)據(jù),然而,隨著現(xiàn)代 Web 應(yīng)用架構(gòu)的演進(jìn),前后端分離(SPA)已成為主流,為了保護(hù)這些接口的安全,開發(fā)者往往會設(shè)置一道門衛(wèi)JWT,所以本文給大家介紹了如何使用Python優(yōu)雅地處理帶有JWT認(rèn)證的接口提交2026-01-01
Python通過正則表達(dá)式選取callback的方法
這篇文章主要介紹了Python通過正則表達(dá)式選取callback的方法,涉及Python正則表達(dá)式及回調(diào)函數(shù)的使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-07-07
Python全自動實(shí)現(xiàn)Excel數(shù)據(jù)分列
在 Excel 數(shù)據(jù)處理中,數(shù)據(jù)分列是高頻剛需操作,本文將使用免費(fèi) Excel 處理庫,通過 Python 實(shí)現(xiàn)全自動單列拆分多列,并對比 Excel 自帶分列與 VBA 方案,幫你快速選出最合適的處理方式2026-04-04
Jupyter?notebook無法鏈接內(nèi)核、運(yùn)行代碼問題
文章主要介紹了在VSCode中使用Jupyter?Notebook遇到的問題及其解決過程,問題包括包版本沖突、文件沖突、路徑錯誤和找不到文件,通過逐一排查和安裝相關(guān)依賴包,最終解決了這些問題,使得Jupyter?Notebook可以在VSCode中正常運(yùn)行2025-02-02
基于Python實(shí)現(xiàn)對PDF文件的OCR識別
大家可能聽說過使用Python進(jìn)行OCR識別操作。在Python中,最出名的庫便是Google所資助的tesseract。利用tesseract可以很輕松地對圖像進(jìn)行識別?,F(xiàn)在問題來了,如果想對一個PDF文檔進(jìn)行OCR識別,該怎么做呢?下面一起來看看。2016-08-08
用Python實(shí)現(xiàn)命令行鬧鐘腳本實(shí)例
今天我們講一下用Python寫的一個小腳本。這是一個可以在命令行運(yùn)行的鬧鐘腳本,對于日常大家工作很實(shí)用,有需要的朋友們可以參考借鑒。2016-09-09

