python 3 http.server 搭建 http 服務

參考:python3 使用http.server模塊 搭建一個簡易的http服務器

程序 server.py :

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()

運行程序:

python server.py

使用瀏覽器訪問,地址:

http://localhost:8888/

注意: self.send_header 輸出的大小的問題可能會導致chrome不能正常地展示內容。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章