使用python3来实现简易web服务

1. python自带web服务

python -m http.server 8001

此时,服务会监听 0.0.0.0:8001。

帮助: server.py [-h] [--cgi] [--bind ADDRESS] [--directory DIRECTORY] [port]

如果不指定directory,则默认当前目录。

2. 进阶

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

 

 
posted @ 2020-03-31 15:07  hacker&haidao  阅读(1645)  评论(0编辑  收藏  举报