python3 http.server模块 搭建简易 http 服务器

在命令行直接运行:

python -m http.server 80
或 python3 -m http.server 80

会看到如下输出:
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...

在浏览器访问会展示运行命令所在目录下的文件
image

通过代码搭建

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

启动服务,在控制台看到:
image
在浏览器输入http://localhost:8888/进行访问:
image

posted @ 2022-10-13 14:18  尘世风  阅读(1445)  评论(0编辑  收藏  举报
*/