python3 http.server模塊 搭建簡易 http 服務器


方法一、代碼調用

示例一

from http.server import HTTPServer, BaseHTTPRequestHandler
import json
 
data = {'result': 'this is a test'}
host = ('localhost', 8888)
 
class Resquest(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write(json.dumps(data).encode())
 
if __name__ == '__main__':
    server = HTTPServer(host, Resquest)
    print("Starting server, listen at: %s:%s" % host)
    server.serve_forever()

啟動服務,在控制台看到:

在瀏覽器輸入http://localhost:8888/進行訪問:

此時查看控制台能看到log已經打印了請求:

示例二 文件服務器

from http.server import HTTPServer, SimpleHTTPRequestHandler
 
if __name__ == '__main__':
    server = HTTPServer(('0.0.0.0', 8888), SimpleHTTPRequestHandler)
    server.serve_forever()

方法二、命令行運行

運行命令:

python3 -m http.server 80
服務器運行后 會以當前命令運行目錄作為http服務器根目錄,

當前環境目錄列表:

[root@106dbd1157b5 ~]# ls -a
.  ..  .bash_history  .bash_logout  .bash_profile  .bashrc  .cache  .cshrc  .pycharm_helpers  .tcshrc  anaconda-ks.cfg

訪問http:

可以看到,當前運行目錄作為http服務器根目錄,列出的文件和系統環境一樣。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM