python3 http.server模块 搭建简易 http和https 服务器
一、搭建http服务器
1、选择服务器根目录
选择一个目录作为http服务器的根目录,并进入。 
2、开启http服务
命令行开启:运行命令 python -m http.server 8888  python程序开启:运行 python tjson.py (命令行),这里在pycharm中运行
from http.server import HTTPServer, SimpleHTTPRequestHandler
if __name__ == '__main__':
server = HTTPServer(('localhost', 8888), SimpleHTTPRequestHandler)
server.serve_forever()

3、本地查看
本地浏览器输入 http://localhost:8888 可以查看简易服务器 
4、非本地查看
运行 ipconfig(window) 或者ifconfig(linux) 查看电脑ip地址。这里为:172.27.18.72  本地浏览器输入 http://172.27.18.72:8888/ 
搭建https服务
这里使用pycharm进行操作,也可直接在命令行中操作
二、选择服务器的根目录
 
安装openssl
查看安装教程
生成证书密钥对
命令行输入 openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem 在该目录下会生成 cert.pem 和 key.pem 两个文件。  
开启https服务
pycharm中运行 h.py 文件 
from http.server import HTTPServer, SimpleHTTPRequestHandler
import ssl
server_ip = 'localhost'
server_port = 5500
server_address = (server_ip, server_port)
httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(httpd.socket, server_side=True, certfile="./cert.pem", keyfile="./key.pem",
ssl_version=ssl.PROTOCOL_TLSv1)
httpd.serve_forever()
或者命令行执行 python h.py 
本地查看
本地浏览器输入 https://localhost:5500 可以查看简易服务器  对比根目录  
非本地查看
参考http中的非本地查看
|