如何使用Python創建簡單的Web服務器
Python自帶HTTP服務器,可快速搭建本地服務。使用python -m http.server 8000命令即可在指定端口啟動文件共享服務,瀏覽器訪問http://localhost:8000查看目錄內容;如需自定義響應,可通過BaseHTTPRequestHandler編寫處理邏輯,運行腳本後實現簡單Web服務,適用於測試與開發,但不推薦用於生產環境。
Python comes with a built-in HTTP server, making it easy to set up a simple web server in seconds—perfect for testing, sharing files, or local development.
Using the Built-in HTTP Server (Python 3)
If you just want to serve files from a directory, Python's http.server module is all you need. No extra installation required.
Follow these steps:
- Open a terminal or command prompt.
- Navigate to the directory you want to serve: cd /path/to/your/folder
- Run the HTTP server on a specific port (eg, 8000): python -m http.server 8000
Now open your browser and go to:
http://localhost:8000You'll see a file listing of the directory. Anyone on your network can access it if your firewall allows the connection.
Creating a Custom Web Server with BaseHTTPServer
If you need more control, like handling specific routes or returning custom responses, you can write a small script using BaseHTTPRequestHandler .
Create a file called server.py with this code:
from http.server import HTTPServer, BaseHTTPRequestHandlerclass SimpleHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b"Hello, this is my web server!")
if __name__ == "__main__":
server = HTTPServer(('localhost', 8000), SimpleHandler)
print("Server running at http://localhost:8000")
server.serve_forever()
Run it with:
python server.pyVisit http://localhost:8000 to see your custom message.
Notes and Tips
This approach works great for learning and basic tasks, but don't use it in production. It's single-threaded and not secure or fast enough for real websites.
- Change localhost to 0.0.0.0 if you want others on your network to access the server.
- Always stop the server with Ctrl C in the terminal.
- Make sure the port you choose isn't already in use.
Basically, that's all it takes to run a simple web server with Python. It's lightweight, quick, and handy when you need something up fast.
以上是如何使用Python創建簡單的Web服務器的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

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

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

Stock Market GPT
人工智慧支援投資研究,做出更明智的決策

熱門文章

熱工具

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

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

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

Dreamweaver CS6
視覺化網頁開發工具

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

運行pipinstall-rrequirements.txt可安裝依賴包,建議先創建並激活虛擬環境以避免衝突,確保文件路徑正確且pip已更新,必要時使用--no-deps或--user等選項調整安裝行為。

Pytest是Python中簡單強大的測試工具,安裝後按命名規則自動發現測試文件。編寫以test_開頭的函數進行斷言測試,使用@pytest.fixture創建可複用的測試數據,通過pytest.raises驗證異常,支持運行指定測試和多種命令行選項,提升測試效率。

theargparsemodulestherecommondedwaywaytohandlecommand-lineargumentsInpython,提供式刺激,typeValidation,helpmessages anderrornhandling; useSudys.argvforsimplecasesRequeRequeRingminimalSetup。

對於數據科學的初學者而言,從“毫無經驗”到“行業專家”的躍遷之路,其核心就是不斷地實踐。而實踐的基礎,正是豐富多樣的數據集。幸運的是,網絡上有大量提供免費公共數據集的網站,它們是提陞技能、磨練技術的寶貴資源。

目錄什麼是比特幣改進提案(BIP)?為什麼BIP如此重要?比特幣改進提案(BIP)的歷史BIP流程如何運作? BIP類型什麼是信號以及礦工如何發出信號? Taproot快速試用BIP的利與弊結語自2011年以來,對比特幣的任何改進都通過稱為比特幣改進提案或“BIP”的系統進行。比特幣改進提案(BIP)為比特幣如何發展提供了指導方針一般來說,BIP有三種可能的類型,其中兩種與比特幣的技術變革有關每個BIP都是從比特幣開發者之間的非正式討論開始的,他們可以在任何地方聚集,包括Twi

大數據分析需側重多核CPU、大容量內存及分層存儲。首選多核處理器如AMDEPYC或RyzenThreadripper,兼顧核心數量與單核性能;內存建議64GB起步,優先選用ECC內存保障數據完整性;存儲采用NVMeSSD(系統與熱數據)、SATASSD(常用數據)和HDD(冷數據)組合,提升整體處理效率。

Import@contextmanagerfromcontextlibanddefineageneratorfunctionthatyieldsexactlyonce,wherecodebeforeyieldactsasenterandcodeafteryield(preferablyinfinally)actsas__exit__.2.Usethefunctioninawithstatement,wheretheyieldedvalueisaccessibleviaas,andthesetup

Identifyrepetitivetasksworthautomating,suchasorganizingfilesorsendingemails,focusingonthosethatoccurfrequentlyandtakesignificanttime.2.UseappropriatePythonlibrarieslikeos,shutil,glob,smtplib,requests,BeautifulSoup,andseleniumforfileoperations,email,w
