目录
一、Python实现Http Server
二、Python实现Https Server
1、利用HTTPServer实现一个简单的Https Server
2、SSL生成证书及密码
一、Python实现Http Server
继承BaseHTTPRequestHandler类,自定义RequestHandler类,实现一个简单的Http Server,以线程方式启动Server,响应GET和POST请求。解析请求中的参数并回复。代码如下所示:
from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn
import ssl
import sys, os
from urllib import parse
from urllib import requestclass RequestHandler(BaseHTTPRequestHandler):def do_POST(self):datas = self.rfile.read(int(self.headers['content-length']))param = datas.decode('utf-8')self.send_content(param.encode('utf-8'),200)def do_GET(self):self.full_path = os.getcwd() + self.pathparam = dict(parse.parse_qsl(self.full_path))if 'mypara' in param.keys():self.send_content(param['mypara'].encode('utf-8'),200)else:msg = '<xml><meta charset="UTF-8">Hello World </xml>'self.send_content(msg.encode('utf-8'),200)def send_content(self, page, status=200):self.send_response(status)self.send_header("Content-type", "text/html")self.send_header("Content-Length", str(len(page)))self.end_headers()self.wfile.write(page)class ThreadingHttpServer ( ThreadingMixIn, HTTPServer ):passif __name__ == '__main__':serverAddress = ('', 80)server = ThreadingHttpServer(serverAddress, RequestHandler)server.serve_forever()
二、Python实现Https Server
1、利用HTTPServer实现一个简单的Https Server
代码如下所示:
#!/usr/bin/env python
# coding: utf-8# In[9]:
from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn
import ssl
import sys, os
from urllib import parse
from urllib import requestclass RequestHandler(BaseHTTPRequestHandler):def do_GET(self):self.full_path = os.getcwd() + self.pathparam = dict(parse.parse_qsl(self.full_path))if 'mypara' in param.keys():self.send_content(param['mypara'].encode('utf-8'),200)else:msg = '<xml><meta charset="UTF-8">Hello World </xml>'self.send_content(msg.encode('utf-8'),200)def send_content(self, page, status=200):self.send_response(status)self.send_header("Content-type", "text/html")self.send_header("Content-Length", str(len(page)))self.end_headers()self.wfile.write(page)if __name__ == '__main__':serverAddress = ('', 443)server = HTTPServer(serverAddress, RequestHandler )server.socket = ssl.wrap_socket(server.socket, certfile='cert.pem', keyfile='key.pem', server_side=True)server.serve_forever()
2、SSL生成证书及密码
安装openssl:apt-get install openssl。
创建测试文件夹testHttps:
# mkdir testHttps
制作自签名证书cert.pem和key.pem,后面代码中要用:
# cd testHttps/
# openssl req -x509 -newkey rsa:4096 -nodes -out cert.pem -keyout key.pem -days 365
查看生成的证书cert.pem和密钥key.pem:
采用上述方式生成的自制证书,浏览器测试访问时,会提示不安全。为了解决安全问题,需要到正规的证书网站申请证书,这里暂时省略此步骤。