方法一、代碼調用
示例一
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服務器根目錄,列出的文件和系統環境一樣。