亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

使用Python創(chuàng)建本地HTTP服務(wù)器實(shí)現(xiàn)與外部系統(tǒng)數(shù)據(jù)對(duì)接的全過(guò)程

 更新時(shí)間:2025年09月14日 13:58:59   作者:yuanpan  
在Python 3.10中創(chuàng)建一個(gè)能夠處理GET和POST請(qǐng)求的本地HTTP服務(wù)器,并提供一個(gè)默認(rèn)的 index.html 頁(yè)面是完全可行的,本文我將提供一個(gè)實(shí)現(xiàn)方案,它包含一個(gè)自定義的請(qǐng)求處理器,并會(huì)說(shuō)明如何創(chuàng)建?index.html?文件,需要的朋友可以參考下

在Python 3.10中創(chuàng)建一個(gè)能夠處理GET和POST請(qǐng)求的本地HTTP服務(wù)器,并提供一個(gè)默認(rèn)的 index.html 頁(yè)面是完全可行的。Python的標(biāo)準(zhǔn)庫(kù)中的 http.server 模塊雖然簡(jiǎn)單,但通過(guò)一些自定義擴(kuò)展可以滿足這個(gè)需求。

下面我將提供一個(gè)實(shí)現(xiàn)方案,它包含一個(gè)自定義的請(qǐng)求處理器,并會(huì)說(shuō)明如何創(chuàng)建 index.html 文件。

Python 3.10 本地HTTP服務(wù)器實(shí)現(xiàn)

下面是一個(gè)使用Python標(biāo)準(zhǔn)庫(kù) http.server 模塊創(chuàng)建本地HTTP服務(wù)器的示例,它可以處理GET和POST請(qǐng)求,并提供一個(gè)默認(rèn)的 index.html 頁(yè)面。

實(shí)現(xiàn)代碼

創(chuàng)建一個(gè)名為 custom_http_server.py 的Python文件,內(nèi)容如下:

from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
import json

class CustomHTTPRequestHandler(BaseHTTPRequestHandler):

    def _set_headers(self, status_code=200, content_type='text/html'):
        """設(shè)置HTTP響應(yīng)頭"""
        self.send_response(status_code)
        self.send_header('Content-type', content_type)
        self.end_headers()

    def do_GET(self):
        """處理GET請(qǐng)求"""
        parsed_path = urlparse(self.path)
        path = parsed_path.path
        
        # 默認(rèn)返回 index.html
        if path == '/' or path == '/index.html':
            try:
                with open('index.html', 'rb') as f:
                    content = f.read()
                self._set_headers(200)
                self.wfile.write(content)
            except FileNotFoundError:
                error_msg = "index.html file not found."
                self._set_headers(404)
                self.wfile.write(error_msg.encode('utf-8'))
        else:
            # 返回請(qǐng)求的路由信息(實(shí)際應(yīng)用中可根據(jù)路徑返回不同內(nèi)容)
            response = {
                'method': 'GET',
                'path': path,
                'query_params': parse_qs(parsed_path.query)
            }
            self._set_headers(200, 'application/json')
            self.wfile.write(json.dumps(response).encode('utf-8'))

    def do_POST(self):
        """處理POST請(qǐng)求"""
        content_length = int(self.headers.get('Content-Length', 0))
        post_data = self.rfile.read(content_length)
        
        # 嘗試解析JSON數(shù)據(jù)(如果Content-Type是application/json)
        if self.headers.get('Content-Type') == 'application/json':
            try:
                parsed_data = json.loads(post_data.decode('utf-8'))
            except json.JSONDecodeError:
                parsed_data = {'raw_data': post_data.decode('utf-8')}
        else:
            # 解析表單數(shù)據(jù)
            parsed_data = parse_qs(post_data.decode('utf-8'))
        
        # 構(gòu)建響應(yīng)
        response = {
            'method': 'POST',
            'path': self.path,
            'data_received': parsed_data
        }
        
        self._set_headers(200, 'application/json')
        self.wfile.write(json.dumps(response, indent=2).encode('utf-8'))

    def do_HEAD(self):
        """處理HEAD請(qǐng)求"""
        self._set_headers()

def run_server(port=8000):
    """啟動(dòng)服務(wù)器"""
    server_address = ('', port)
    httpd = HTTPServer(server_address, CustomHTTPRequestHandler)
    print(f'Starting server on port {port}...')
    print(f'Access your server at http://localhost:{port}')
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print('\nShutting down server...')
        httpd.shutdown()

if __name__ == '__main__':
    run_server()

創(chuàng)建默認(rèn)的 index.html 頁(yè)面

在同一目錄下創(chuàng)建一個(gè) index.html 文件:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Python HTTP 服務(wù)器</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
        }
        .api-info {
            background-color: #f9f9f9;
            padding: 15px;
            border-left: 4px solid #4CAF50;
            margin: 20px 0;
        }
        .endpoint {
            margin: 15px 0;
        }
        code {
            background-color: #eee;
            padding: 2px 5px;
            border-radius: 3px;
            font-family: monospace;
        }
        .try-button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>歡迎使用Python HTTP服務(wù)器</h1>
        <p>這是一個(gè)簡(jiǎn)單的本地服務(wù)器,用于演示如何處理GET和POST請(qǐng)求。</p>
        
        <div class="api-info">
            <h2>API端點(diǎn)示例:</h2>
            
            <div class="endpoint">
                <h3>GET /api/data</h3>
                <p>獲取示例數(shù)據(jù)</p>
                <button class="try-button" οnclick="testGet()">測(cè)試GET請(qǐng)求</button>
                <pre id="get-response"></pre>
            </div>
            
            <div class="endpoint">
                <h3>POST /api/data</h3>
                <p>提交數(shù)據(jù)到服務(wù)器</p>
                <button class="try-button" οnclick="testPost()">測(cè)試POST請(qǐng)求</button>
                <pre id="post-response"></pre>
            </div>
        </div>
    </div>

    <script>
        async function testGet() {
            try {
                const response = await fetch('/api/data?name=Test&value=123');
                const data = await response.json();
                document.getElementById('get-response').textContent = JSON.stringify(data, null, 2);
            } catch (error) {
                console.error('Error:', error);
            }
        }

        async function testPost() {
            try {
                const response = await fetch('/api/data', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        name: '示例數(shù)據(jù)',
                        value: 456,
                        timestamp: new Date().toISOString()
                    })
                });
                const data = await response.json();
                document.getElementById('post-response').textContent = JSON.stringify(data, null, 2);
            } catch (error) {
                console.error('Error:', error);
            }
        }
    </script>
</body>
</html>

運(yùn)行服務(wù)器

  • 將上述兩段代碼分別保存為 custom_http_server.py 和 index.html,放在同一目錄下。
  • 打開(kāi)終端或命令提示符,導(dǎo)航到該目錄。
  • 運(yùn)行以下命令啟動(dòng)服務(wù)器:
python custom_http_server.py
  • 服務(wù)器將在默認(rèn)端口8000上啟動(dòng)。如需指定其他端口,可以修改 run_server() 函數(shù)調(diào)用,例如 run_server(8080)。
  • 打開(kāi)瀏覽器訪問(wèn) http://localhost:8000,你將看到默認(rèn)的 index.html 頁(yè)面。

功能說(shuō)明

GET請(qǐng)求處理

  • 訪問(wèn)根路徑(/ 或 /index.html)會(huì)返回 index.html 文件內(nèi)容。
  • 訪問(wèn)其他路徑(如 /api/data)會(huì)返回一個(gè)JSON響應(yīng),包含請(qǐng)求的路徑和查詢參數(shù)。

POST請(qǐng)求處理

  • 支持接收表單數(shù)據(jù)(application/x-www-form-urlencoded)和JSON數(shù)據(jù)(application/json)。
  • 服務(wù)器會(huì)解析接收到的數(shù)據(jù)并以JSON格式返回,包含請(qǐng)求的路徑和接收到的數(shù)據(jù)。

靜態(tài)文件服務(wù)

  • 服務(wù)器可以提供其他靜態(tài)文件(如CSS、JS、圖片),只需將這些文件放在與服務(wù)器腳本相同的目錄下,然后通過(guò)瀏覽器訪問(wèn)(例如 http://localhost:8000/filename)即可。

注意事項(xiàng)

  • 開(kāi)發(fā)環(huán)境專(zhuān)用:此服務(wù)器僅適用于開(kāi)發(fā)和測(cè)試環(huán)境。它不具備生產(chǎn)環(huán)境所需的安全性和性能特性。
  • 安全性:此實(shí)現(xiàn)沒(méi)有身份驗(yàn)證機(jī)制、不支持HTTPS加密,且缺乏請(qǐng)求過(guò)濾功能。
  • 性能:該服務(wù)器是單線程的,在高并發(fā)情況下性能有限。對(duì)于生產(chǎn)環(huán)境,建議使用專(zhuān)業(yè)的Web服務(wù)器如Nginx、Apache或Python Web框架(如Flask、Django)。

這個(gè)實(shí)現(xiàn)提供了一個(gè)基礎(chǔ)框架,你可以根據(jù)實(shí)際需求進(jìn)一步擴(kuò)展功能,例如添加更多路由、實(shí)現(xiàn)文件上傳或連接數(shù)據(jù)庫(kù)等。

以上就是使用Python創(chuàng)建本地HTTP服務(wù)器實(shí)現(xiàn)與外部系統(tǒng)數(shù)據(jù)對(duì)接的全過(guò)程的詳細(xì)內(nèi)容,更多關(guān)于Python創(chuàng)建本地HTTP服務(wù)器的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • windows系統(tǒng)上通過(guò)whl文件安裝triton模塊的簡(jiǎn)單步驟

    windows系統(tǒng)上通過(guò)whl文件安裝triton模塊的簡(jiǎn)單步驟

    這篇文章主要介紹了在Windows系統(tǒng)中通過(guò).whl文件安裝Triton的步驟,包括確認(rèn)系統(tǒng)環(huán)境、下載合適的.whl文件、使用pip安裝、驗(yàn)證安裝、使用Triton以及解決潛在問(wèn)題,需要的朋友可以參考下
    2025-01-01
  • Python使用matplotlib繪制三維圖形示例

    Python使用matplotlib繪制三維圖形示例

    這篇文章主要介紹了Python使用matplotlib繪制三維圖形,結(jié)合實(shí)例形式分析了Python基于matplotlib庫(kù)繪制三維圖形的相關(guān)操作技巧與注意事項(xiàng),需要的朋友可以參考下
    2018-08-08
  • 在python 不同時(shí)區(qū)之間的差值與轉(zhuǎn)換方法

    在python 不同時(shí)區(qū)之間的差值與轉(zhuǎn)換方法

    今天小編就為大家分享一篇在python 不同時(shí)區(qū)之間的差值與轉(zhuǎn)換方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-01-01
  • Python實(shí)現(xiàn)的搖骰子猜大小功能小游戲示例

    Python實(shí)現(xiàn)的搖骰子猜大小功能小游戲示例

    這篇文章主要介紹了Python實(shí)現(xiàn)的搖骰子猜大小功能小游戲,涉及Python隨機(jī)數(shù)運(yùn)算與數(shù)值判斷相關(guān)操作技巧,需要的朋友可以參考下
    2017-12-12
  • python八種降維方法匯總

    python八種降維方法匯總

    在Python中,有多種降維方法可以使用,本文就來(lái)介紹八種降維方法以及使用場(chǎng)景,具有一定的參考價(jià)值,感興趣的可以一下,感興趣的可以了解一下
    2023-10-10
  • 利用Python統(tǒng)計(jì)Jira數(shù)據(jù)并可視化

    利用Python統(tǒng)計(jì)Jira數(shù)據(jù)并可視化

    目前公司使用 Jira 作為項(xiàng)目管理工具,在每一次迭代完成后的復(fù)盤(pán)會(huì)上,我們都需要針對(duì)本次迭代的 Bug 進(jìn)行數(shù)據(jù)統(tǒng)計(jì),以幫助管理層能更直觀的了解研發(fā)的代碼質(zhì)量。本篇文章將介紹如何利用統(tǒng)計(jì) Jira 數(shù)據(jù),并進(jìn)行可視化,需要的可以參考一下
    2022-07-07
  • pandas DataFrame行或列的刪除方法的實(shí)現(xiàn)示例

    pandas DataFrame行或列的刪除方法的實(shí)現(xiàn)示例

    這篇文章主要介紹了pandas DataFrame行或列的刪除方法的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-08-08
  • numpy中的nan和inf,及其批量判別、替換方式

    numpy中的nan和inf,及其批量判別、替換方式

    在Numpy中,NaN表示非數(shù)值,Inf表示無(wú)窮大,NaN與任何值計(jì)算都是NaN,Inf與0相乘是NaN,其余情況下與Inf運(yùn)算仍為Inf,可以使用np.isnan(), np.isinf(), np.isneginf(), np.isposinf(), np.isfinite()等函數(shù)進(jìn)行批量判別,返回布爾值數(shù)組
    2024-09-09
  • Python Matplotlib 基于networkx畫(huà)關(guān)系網(wǎng)絡(luò)圖

    Python Matplotlib 基于networkx畫(huà)關(guān)系網(wǎng)絡(luò)圖

    這篇文章主要介紹了Python Matplotlib 基于networkx畫(huà)關(guān)系網(wǎng)絡(luò)圖,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-07-07
  • python腳本替換指定行實(shí)現(xiàn)步驟

    python腳本替換指定行實(shí)現(xiàn)步驟

    這篇文章主要介紹了 python腳本替換指定行實(shí)現(xiàn)步驟的相關(guān)資料,需要的朋友可以參考下
    2017-07-07

最新評(píng)論