Python如何實現(xiàn) HTTP echo 服務器
更新時間:2025年01月06日 11:36:44 作者:Toormi
本文介紹了如何使用Python實現(xiàn)一個簡單的HTTPecho服務器,該服務器支持GET和POST請求,并返回JSON格式的響應,GET請求返回請求路徑、方法、頭和查詢字符串,POST請求還返回請求體內(nèi)容,服務器的使用方法和測試示例也一并提供,感興趣的朋友跟隨小編一起看看吧
一個用來做測試的簡單的 HTTP echo 服務器。
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
class EchoHandler(BaseHTTPRequestHandler):
def do_GET(self):
# 構造響應數(shù)據(jù)
response_data = {
'path': self.path,
'method': 'GET',
'headers': dict(self.headers),
'query_string': self.path.split('?')[1] if '?' in self.path else ''
}
# 設置響應頭
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
# 發(fā)送響應
self.wfile.write(json.dumps(response_data, indent=2).encode())
def do_POST(self):
# 獲取請求體長度
content_length = int(self.headers.get('Content-Length', 0))
# 讀取請求體
body = self.rfile.read(content_length).decode()
# 構造響應數(shù)據(jù)
response_data = {
'path': self.path,
'method': 'POST',
'headers': dict(self.headers),
'body': body
}
# 設置響應頭
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
# 發(fā)送響應
self.wfile.write(json.dumps(response_data, indent=2).encode())
def run_server(port=8000):
server_address = ('', port)
httpd = HTTPServer(server_address, EchoHandler)
print(f'Starting server on port {port}...')
httpd.serve_forever()
if __name__ == '__main__':
run_server()這個 HTTP echo 服務器的特點:
- 支持 GET 和 POST 請求
- 返回 JSON 格式的響應
- 對于 GET 請求,會返回:
- 請求路徑
- 請求方法
- 請求頭
- 查詢字符串
- 對于 POST 請求,額外返回請求體內(nèi)容
使用方法:
- 運行腳本啟動服務器
- 使用瀏覽器或 curl 訪問
http://localhost:8000
測試示例:
# GET 請求 curl http://localhost:8000/test?foo=bar # POST 請求 curl -X POST -d "hello=world" http://localhost:8000/test
到此這篇關于Python實現(xiàn)一個簡單的 HTTP echo 服務器的文章就介紹到這了,更多相關Python HTTP echo 服務器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python3中configparser模塊讀寫ini文件并解析配置的用法詳解
這篇文章主要介紹了Python3中configparser模塊讀寫ini文件并解析配置的用法詳解,需要的朋友可以參考下2020-02-02
使用Python的DrissionPage庫設置代理IP的詳細流程
DrissionPage 是一個基于 Playwright 和 Requests 的高效網(wǎng)頁抓取工具,它簡化了 Web 自動化、瀏覽器操作和抓取任務,通過 DrissionPage,用戶可以輕松地使用代理 IP 來隱藏真實的請求來源,本文給大家介紹了如何使用Python的DrissionPage庫設置代理IP2025-07-07
Python實現(xiàn)二叉樹的常見遍歷操作總結【7種方法】
這篇文章主要介紹了Python實現(xiàn)二叉樹的常見遍歷操作,結合實例形式總結分析了二叉樹的前序、中序、后序、層次遍歷中的迭代與遞歸等7種操作方法,需要的朋友可以參考下2019-03-03
Python數(shù)學建模PuLP庫線性規(guī)劃入門示例詳解
這篇文章主要為大家介紹了Python數(shù)學建模PuLP庫線性規(guī)劃入門示例詳解,想學習關于Python建模的同學可以學習參考下,希望能夠有所幫助2021-10-10

