如何使用 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>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>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>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
將以下程式碼貼到其中
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Python Simple Server</title> </head> <body> <h1>Welcome to My Python Server!</h1> <p>This is a simple web server running on your local device.</p> </body> </html>
第 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中文網其他相關文章!

熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

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

Python更易學且易用,C 則更強大但複雜。 1.Python語法簡潔,適合初學者,動態類型和自動內存管理使其易用,但可能導致運行時錯誤。 2.C 提供低級控制和高級特性,適合高性能應用,但學習門檻高,需手動管理內存和類型安全。

每天學習Python兩個小時是否足夠?這取決於你的目標和學習方法。 1)制定清晰的學習計劃,2)選擇合適的學習資源和方法,3)動手實踐和復習鞏固,可以在這段時間內逐步掌握Python的基本知識和高級功能。

Python在開發效率上優於C ,但C 在執行性能上更高。 1.Python的簡潔語法和豐富庫提高開發效率。 2.C 的編譯型特性和硬件控制提升執行性能。選擇時需根據項目需求權衡開發速度與執行效率。

Python和C 各有優勢,選擇應基於項目需求。 1)Python適合快速開發和數據處理,因其簡潔語法和動態類型。 2)C 適用於高性能和系統編程,因其靜態類型和手動內存管理。

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

Python在自動化、腳本編寫和任務管理中表現出色。 1)自動化:通過標準庫如os、shutil實現文件備份。 2)腳本編寫:使用psutil庫監控系統資源。 3)任務管理:利用schedule庫調度任務。 Python的易用性和豐富庫支持使其在這些領域中成為首選工具。

Python在科學計算中的應用包括數據分析、機器學習、數值模擬和可視化。 1.Numpy提供高效的多維數組和數學函數。 2.SciPy擴展Numpy功能,提供優化和線性代數工具。 3.Pandas用於數據處理和分析。 4.Matplotlib用於生成各種圖表和可視化結果。

Python在Web開發中的關鍵應用包括使用Django和Flask框架、API開發、數據分析與可視化、機器學習與AI、以及性能優化。 1.Django和Flask框架:Django適合快速開發複雜應用,Flask適用於小型或高度自定義項目。 2.API開發:使用Flask或DjangoRESTFramework構建RESTfulAPI。 3.數據分析與可視化:利用Python處理數據並通過Web界面展示。 4.機器學習與AI:Python用於構建智能Web應用。 5.性能優化:通過異步編程、緩存和代碼優
