Python如何實現(xiàn) HTTP echo 服務(wù)器
更新時間:2025年01月06日 11:36:44 作者:Toormi
本文介紹了如何使用Python實現(xiàn)一個簡單的HTTPecho服務(wù)器,該服務(wù)器支持GET和POST請求,并返回JSON格式的響應(yīng),GET請求返回請求路徑、方法、頭和查詢字符串,POST請求還返回請求體內(nèi)容,服務(wù)器的使用方法和測試示例也一并提供,感興趣的朋友跟隨小編一起看看吧
一個用來做測試的簡單的 HTTP echo 服務(wù)器。
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
class EchoHandler(BaseHTTPRequestHandler):
def do_GET(self):
# 構(gòu)造響應(yīng)數(shù)據(jù)
response_data = {
'path': self.path,
'method': 'GET',
'headers': dict(self.headers),
'query_string': self.path.split('?')[1] if '?' in self.path else ''
}
# 設(shè)置響應(yīng)頭
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
# 發(fā)送響應(yīng)
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()
# 構(gòu)造響應(yīng)數(shù)據(jù)
response_data = {
'path': self.path,
'method': 'POST',
'headers': dict(self.headers),
'body': body
}
# 設(shè)置響應(yīng)頭
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
# 發(fā)送響應(yīng)
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 服務(wù)器的特點:
- 支持 GET 和 POST 請求
- 返回 JSON 格式的響應(yīng)
- 對于 GET 請求,會返回:
- 請求路徑
- 請求方法
- 請求頭
- 查詢字符串
- 對于 POST 請求,額外返回請求體內(nèi)容
使用方法:
- 運行腳本啟動服務(wù)器
- 使用瀏覽器或 curl 訪問
http://localhost:8000
測試示例:
# GET 請求 curl http://localhost:8000/test?foo=bar # POST 請求 curl -X POST -d "hello=world" http://localhost:8000/test
到此這篇關(guān)于Python實現(xiàn)一個簡單的 HTTP echo 服務(wù)器的文章就介紹到這了,更多相關(guān)Python HTTP echo 服務(wù)器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
在pycharm中debug 實時查看數(shù)據(jù)操作(交互式)
這篇文章主要介紹了在pycharm中debug 實時查看數(shù)據(jù)操作(交互式),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
Python中的getter與setter及deleter使用示例講解
這篇文章主要介紹了Python中的getter與setter及deleter使用方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-01-01

