Python如何實(shí)現(xiàn) HTTP echo 服務(wù)器
一個(gè)用來做測試的簡單的 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()
這個(gè) HTTP echo 服務(wù)器的特點(diǎn):
- 支持 GET 和 POST 請求
- 返回 JSON 格式的響應(yīng)
- 對于 GET 請求,會返回:
- 請求路徑
- 請求方法
- 請求頭
- 查詢字符串
- 對于 POST 請求,額外返回請求體內(nèi)容
使用方法:
- 運(yùn)行腳本啟動(dòng)服務(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實(shí)現(xiàn)一個(gè)簡單的 HTTP echo 服務(wù)器的文章就介紹到這了,更多相關(guān)Python HTTP echo 服務(wù)器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python3搭建http服務(wù)器的實(shí)現(xiàn)代碼
- 淺析使用Python搭建http服務(wù)器
- Python代碼實(shí)現(xiàn)http/https代理服務(wù)器的腳本
- 使用 Python 快速實(shí)現(xiàn) HTTP 和 FTP 服務(wù)器的方法
- 使用Python創(chuàng)建簡單的HTTP服務(wù)器的方法步驟
- python 使用poster模塊進(jìn)行http方式的文件傳輸?shù)椒?wù)器的方法
- 用Python一鍵搭建Http服務(wù)器的方法
- python 請求服務(wù)器的實(shí)現(xiàn)代碼(http請求和https請求)
相關(guān)文章
十個(gè)常見的Python腳本詳細(xì)介紹及代碼舉例
這篇文章主要給大家介紹了十個(gè)常見的Python腳本的相關(guān)資料,包括批量重命名文件、下載網(wǎng)頁圖片、發(fā)送郵件通知、讀取和寫入CSV文件、爬取網(wǎng)頁數(shù)據(jù)、自動(dòng)化測試、圖像處理、數(shù)據(jù)可視化以及創(chuàng)建簡單的Web應(yīng)用,需要的朋友可以參考下2024-11-11在pycharm中debug 實(shí)時(shí)查看數(shù)據(jù)操作(交互式)
這篇文章主要介紹了在pycharm中debug 實(shí)時(shí)查看數(shù)據(jù)操作(交互式),具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06Python中的getter與setter及deleter使用示例講解
這篇文章主要介紹了Python中的getter與setter及deleter使用方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-01-01python模擬點(diǎn)擊在ios中實(shí)現(xiàn)的實(shí)例講解
在本篇文章里小編給大家整理的是一篇關(guān)于python模擬點(diǎn)擊在ios中實(shí)現(xiàn)的實(shí)例講解內(nèi)容,有需要的朋友們可以參考下。2020-11-11