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服务器根目录,列出的文件和系统环境一样。

原文地址:https://www.cnblogs.com/xiaomage666/p/15404592.html