欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用Python自建輕量級的HTTP調試工具

 更新時間:2025年04月08日 15:44:35   作者:傻啦嘿喲  
這篇文章主要為大家詳細介紹了如何使用Python自建一個輕量級的HTTP調試工具,文中的示例代碼講解詳細,感興趣的小伙伴可以參考一下

一、為什么需要自建工具

當 Postman 變得臃腫,當我們需要快速驗證一個 API 而不想打開瀏覽器,或者團隊需要定制特定功能時,用 Python 自建 HTTP 調試工具成為優(yōu)雅選擇。本文將用 300 行代碼實現(xiàn)核心功能,兼顧實用性與可維護性。

二、核心功能設計

請求發(fā)送:支持 GET/POST/PUT/DELETE 等方法

參數(shù)管理:Query Params、Form-data、JSON Body

響應解析:自動格式化 JSON/XML,顯示狀態(tài)碼和耗時

歷史記錄:保存最近 100 條請求記錄

環(huán)境變量:支持.env 文件配置基礎 URL

三、技術選型

服務端:Flask(輕量簡單) + requests(請求發(fā)送)

數(shù)據(jù)存儲:JSON 文件(記錄請求歷史)

環(huán)境配置:python-dotenv(.env 文件支持)

交互界面:Rich 庫(終端美化)

四、分步實現(xiàn)

第一步:搭建基礎框架

from flask import Flask, request, jsonify
import requests
from rich.console import Console
from rich.panel import Panel
import json
import os
from dotenv import load_dotenv
 
app = Flask(__name__)
console = Console()
load_dotenv()  # 加載環(huán)境變量

第二步:實現(xiàn)請求轉發(fā)邏輯

@app.route('/api/proxy', methods=['POST'])
def proxy():
    # 解析請求參數(shù)
    target_url = request.json.get('url')
    method = request.json.get('method', 'GET')
    headers = request.json.get('headers', {})
    data = request.json.get('data')
    
    # 發(fā)送請求
    try:
        if method == 'GET':
            resp = requests.get(target_url, headers=headers, params=data)
        elif method == 'POST':
            resp = requests.post(target_url, headers=headers, json=data)
        # 其他方法類似處理...
        
        # 記錄請求
        save_request_history({
            'url': target_url,
            'method': method,
            'status': resp.status_code,
            'time': resp.elapsed.total_seconds()
        })
        
        return format_response(resp)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

第三步:響應格式化處理

def format_response(resp):
    content_type = resp.headers.get('Content-Type', '')
    
    if 'application/json' in content_type:
        try:
            pretty_json = json.dumps(resp.json(), indent=2, ensure_ascii=False)
            return Panel(pretty_json, title=f"[bold green]Status: {resp.status_code}")
        except:
            return Panel(resp.text, title=f"[bold yellow]Raw Response")
    elif 'xml' in content_type:
        return Panel(resp.text, title=f"[bold blue]XML Response")
    else:
        return Panel(resp.text, title=f"[bold magenta]Text Response")

第四步:歷史記錄存儲

HISTORY_FILE = 'request_history.json'
 
def save_request_history(record):
    try:
        if os.path.exists(HISTORY_FILE):
            with open(HISTORY_FILE) as f:
                history = json.load(f)
        else:
            history = []
            
        history.insert(0, record)
        if len(history) > 100:
            history.pop()
            
        with open(HISTORY_FILE, 'w') as f:
            json.dump(history, f, indent=2)
    except Exception as e:
        console.print(f"[bold red]Error saving history: {str(e)}")

五、進階優(yōu)化技巧

1. 環(huán)境變量管理

創(chuàng)建 .env 文件:

BASE_URL=https://api.example.com
TIMEOUT=10

代碼中讀?。?/p>

base_url = os.getenv('BASE_URL', 'http://localhost')
timeout = int(os.getenv('TIMEOUT', 5))

2. 請求模板功能

創(chuàng)建 templates.json:

{
    "user_login": {
        "url": "/auth/login",
        "method": "POST",
        "headers": {"Content-Type": "application/json"},
        "body": {"username": "admin", "password": "123456"}
    }
}

添加模板調用接口:

@app.route('/api/templates', methods=['GET'])
def list_templates():
    with open('templates.json') as f:
        return jsonify(json.load(f))
 
@app.route('/api/execute_template', methods=['POST'])
def execute_template():
    template_name = request.json.get('template')
    # 加載并執(zhí)行模板...

3. 性能優(yōu)化

使用連接池:

requests.adapters.HTTPAdapter(pool_connections=10, pool_maxsize=10)

異步支持(改用 FastAPI):

from fastapi import FastAPI, Request
 
@app.post("/async-proxy")
async def async_proxy(request: Request):
    # 使用 httpx 異步客戶端

六、使用示例

場景1:發(fā)送 GET 請求

curl -X POST http://localhost:5000/api/proxy \
-H "Content-Type: application/json" \
-d '{
    "url": "https://jsonplaceholder.typicode.com/posts/1",
    "method": "GET"
}'

響應:

[bold green]Status: 200
{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

場景2:發(fā)送 POST 請求

curl -X POST http://localhost:5000/api/proxy \
-H "Content-Type: application/json" \
-d '{
    "url": "https://jsonplaceholder.typicode.com/posts",
    "method": "POST",
    "headers": {"X-Custom-Header": "test"},
    "data": {"title": "foo", "body": "bar", "userId": 1}
}'

響應:

[bold green]Status: 201
{
    "title": "foo",
    "body": "bar",
    "userId": 1,
    "id": 101
}

七、性能對比

特性自建工具Postman
啟動速度< 0.1s~2s
內存占用~10MB~200MB
定制化能力完全控制插件擴展
團隊協(xié)作需自行實現(xiàn)內置協(xié)作功能
自動化測試需結合 unittest內置測試集合

八、擴展方向建議

可視化界面:用 PyQt/Tkinter 添加簡單 GUI

自動化測試:集成 pytest 生成測試報告

監(jiān)控報警:添加響應時間/狀態(tài)碼異常告警

文檔生成:根據(jù)請求歷史自動生成 API 文檔

九、總結

這個輕量級工具在以下場景特別適用:

  • 快速驗證 API 修改
  • 調試內部測試環(huán)境
  • 需要定制特殊請求邏輯
  • 教學演示(展示 HTTP 原理)

對于需要復雜集合測試、Mock 服務器等高級功能的場景,仍建議使用 Postman 等成熟工具。但自建工具帶來的靈活性和性能優(yōu)勢,在特定場景下會成為開發(fā)效率的提升利器。

到此這篇關于使用Python自建輕量級的HTTP調試工具的文章就介紹到這了,更多相關Python HTTP調試內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • python讀取TXT每行,并存到LIST中的方法

    python讀取TXT每行,并存到LIST中的方法

    今天小編就為大家分享一篇python讀取TXT每行,并存到LIST中的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-10-10
  • 使用Python中的cookielib模擬登錄網站

    使用Python中的cookielib模擬登錄網站

    這篇文章主要介紹了使用Python中的cookielib模擬登錄網站,用作生成cookie然后登錄,需要的朋友可以參考下
    2015-04-04
  • Django自定義認證方式用法示例

    Django自定義認證方式用法示例

    這篇文章主要介紹了Django自定義認證方式用法,結合實例形式分析了Django自定義認證的創(chuàng)建、設置及功能實現(xiàn)技巧,需要的朋友可以參考下
    2017-06-06
  • Python中 Lambda表達式全面解析

    Python中 Lambda表達式全面解析

    Lambda是一種匿名函數(shù),當我們需要重復調用某一函數(shù),又不想寫那么多代碼時可以使用lambda表達式來代替。本文給大家介紹Python中 Lambda表達式,需要的朋友一起學習吧
    2016-11-11
  • 使用Python橫向合并excel文件的實例

    使用Python橫向合并excel文件的實例

    今天小編就為大家分享一篇使用Python橫向合并excel文件的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-12-12
  • 基于pyinstaller超級加密操作(加殼和轉c)

    基于pyinstaller超級加密操作(加殼和轉c)

    這篇文章主要介紹了基于pyinstaller超級加密操作 (加殼和轉c),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-03-03
  • 使用PIL(Python-Imaging)反轉圖像的顏色方法

    使用PIL(Python-Imaging)反轉圖像的顏色方法

    今天小編就為大家分享一篇使用PIL(Python-Imaging)反轉圖像的顏色方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-01-01
  • Python中l(wèi)ogging日志模塊代碼調試過程詳解

    Python中l(wèi)ogging日志模塊代碼調試過程詳解

    這篇文章主要介紹了Python中l(wèi)ogging日志模塊代碼調試,今天來看看如何在代碼中定義日志,并探討日志的權限,需要的朋友可以參考下
    2023-04-04
  • python 獲取當天凌晨零點的時間戳方法

    python 獲取當天凌晨零點的時間戳方法

    今天小編就為大家分享一篇python 獲取當天凌晨零點的時間戳方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-05-05
  • Django實戰(zhàn)之用戶認證(用戶登錄與注銷)

    Django實戰(zhàn)之用戶認證(用戶登錄與注銷)

    這篇文章主要介紹了Django實戰(zhàn)之用戶認證(用戶登錄與注銷),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-07-07

最新評論