搜尋
首頁後端開發Python教學如何使用 Python 將您的裝置變成簡單的伺服器。

How to Turn Your Device Into a Simple Server Using Python.

作者:Trix Cyrus

讓我們建立一個從您的裝置託管的 Python 伺服器。

開始..

建立一個名為server的目錄

mkdir server

建立一個名為 server.py 的檔案

nano server.py

貼上以下程式碼。

import http.server
import socketserver
import logging
import os
import threading
from urllib.parse import urlparse, parse_qs

PORT = 8080
DIRECTORY = "www"  

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')

class MyHandler(http.server.SimpleHTTPRequestHandler):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=DIRECTORY, **kwargs)

    def log_message(self, format, *args):
        logging.info("%s - %s" % (self.client_address[0], format % args))

    def do_GET(self):
        parsed_path = urlparse(self.path)
        query = parse_qs(parsed_path.query)

        # Custom logic for different routes
        if parsed_path.path == '/':
            self.serve_file("index.html")
        elif parsed_path.path == '/about':
            self.respond_with_text("<h1 id="About-Us">About Us</h1><p>This is a custom Python server.</p>")
        elif parsed_path.path == '/greet':
            name = query.get('name', ['stranger'])[0]
            self.respond_with_text(f"<h1 id="Hello-name">Hello, {name}!</h1>")
        else:
            self.send_error(404, "File Not Found")

    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(content_length)
        logging.info("Received POST data: %s", post_data.decode('utf-8'))
        self.respond_with_text("<h1 id="POST-request-received">POST request received</h1>")

    def serve_file(self, filename):
        if os.path.exists(os.path.join(DIRECTORY, filename)):
            self.send_response(200)
            self.send_header("Content-type", "text/html")
            self.end_headers()
            with open(os.path.join(DIRECTORY, filename), 'rb') as file:
                self.wfile.write(file.read())
        else:
            self.send_error(404, "File Not Found")

    def respond_with_text(self, content):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(content.encode('utf-8'))

class ThreadedHTTPServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
    daemon_threads = True  # Handle requests in separate threads

def run_server():
    try:
        with ThreadedHTTPServer(("", PORT), MyHandler) as httpd:
            logging.info(f"Serving HTTP on port {PORT}")
            logging.info(f"Serving files from directory: {DIRECTORY}")
            httpd.serve_forever()
    except Exception as e:
        logging.error(f"Error starting server: {e}")
    except KeyboardInterrupt:
        logging.info("Server stopped by user")

if __name__ == "__main__":
    server_thread = threading.Thread(target=run_server)
    server_thread.start()

    server_thread.join()

建立一個名為www的目錄

mkdir www

現在導航到 www 目錄

cd www

建立一個名為index.html的檔案

nano index.html

將以下程式碼貼到其中



    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Python Simple Server</title>


    <h1 id="Welcome-to-My-Python-Server">Welcome to My Python Server!</h1>
    <p>This is a simple web server running on your local device.</p>


第 2 步:測試路由

執行修改後的腳本後,請前往:

http://localhost:8080/ 查看首頁。
http://localhost:8080/about 查看關於頁面。
http://localhost:8080/greet?name=Trix
對於任何其他路徑,伺服器將傳回 404 錯誤。

下面是目錄結構

server/
├── server.py
└── www/
    └── index.html

在遠端設備上運行伺服器

如果您想從同一網路上的另一台裝置存取您的 Python 伺服器怎麼辦?您可以透過尋找執行伺服器的電腦的本機 IP 位址並使用它而不是 localhost 來輕鬆完成此操作。

第 1 步:尋找您的 IP 位址

使用類似
的指令

ipconfig
ifconfig

尋找您的 IPv4 位址(例如 192.168.x.x)。

步驟 2. 修改您的伺服器腳本

在您的伺服器腳本中,替換啟動伺服器的行:

with ThreadedHTTPServer(("", PORT), MyHandler) as httpd:

改為:

with ThreadedHTTPServer(("0.0.0.0", PORT), MyHandler) as httpd:

第 3 步:從另一台裝置存取伺服器

現在,使用您之前找到的 IP 位址,您可以透過瀏覽器中的 http://:8080 從同一網路上的任何裝置存取伺服器。

一切就緒

~TrixSec

以上是如何使用 Python 將您的裝置變成簡單的伺服器。的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python中的合併列表:選擇正確的方法Python中的合併列表:選擇正確的方法May 14, 2025 am 12:11 AM

Tomergelistsinpython,YouCanusethe操作員,estextMethod,ListComprehension,Oritertools

如何在Python 3中加入兩個列表?如何在Python 3中加入兩個列表?May 14, 2025 am 12:09 AM

在Python3中,可以通過多種方法連接兩個列表:1)使用 運算符,適用於小列表,但對大列表效率低;2)使用extend方法,適用於大列表,內存效率高,但會修改原列表;3)使用*運算符,適用於合併多個列表,不修改原列表;4)使用itertools.chain,適用於大數據集,內存效率高。

Python串聯列表字符串Python串聯列表字符串May 14, 2025 am 12:08 AM

使用join()方法是Python中從列表連接字符串最有效的方法。 1)使用join()方法高效且易讀。 2)循環使用 運算符對大列表效率低。 3)列表推導式與join()結合適用於需要轉換的場景。 4)reduce()方法適用於其他類型歸約,但對字符串連接效率低。完整句子結束。

Python執行,那是什麼?Python執行,那是什麼?May 14, 2025 am 12:06 AM

pythonexecutionistheprocessoftransformingpypythoncodeintoExecutablestructions.1)InternterPreterReadSthecode,ConvertingTingitIntObyTecode,whepythonvirtualmachine(pvm)theglobalinterpreterpreterpreterpreterlock(gil)the thepythonvirtualmachine(pvm)

Python:關鍵功能是什麼Python:關鍵功能是什麼May 14, 2025 am 12:02 AM

Python的關鍵特性包括:1.語法簡潔易懂,適合初學者;2.動態類型系統,提高開發速度;3.豐富的標準庫,支持多種任務;4.強大的社區和生態系統,提供廣泛支持;5.解釋性,適合腳本和快速原型開發;6.多範式支持,適用於各種編程風格。

Python:編譯器還是解釋器?Python:編譯器還是解釋器?May 13, 2025 am 12:10 AM

Python是解釋型語言,但也包含編譯過程。 1)Python代碼先編譯成字節碼。 2)字節碼由Python虛擬機解釋執行。 3)這種混合機制使Python既靈活又高效,但執行速度不如完全編譯型語言。

python用於循環與循環時:何時使用哪個?python用於循環與循環時:何時使用哪個?May 13, 2025 am 12:07 AM

UseeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.forloopsareIdealForkNownsences,而WhileLeleLeleLeleLeleLoopSituationSituationsItuationsItuationSuationSituationswithUndEtermentersitations。

Python循環:最常見的錯誤Python循環:最常見的錯誤May 13, 2025 am 12:07 AM

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐個偏置,零indexingissues,andnestedloopineflinefficiencies

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)