您的位置:首页 > 文旅 > 旅游 > Python实现Http Server及Https Server

Python实现Http Server及Https Server

2024/12/23 10:08:12 来源:https://blog.csdn.net/catontower/article/details/141572402  浏览:    关键词:Python实现Http Server及Https Server

目录

一、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:

采用上述方式生成的自制证书,浏览器测试访问时,会提示不安全。为了解决安全问题,需要到正规的证书网站申请证书,这里暂时省略此步骤。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com