最近学习了python HTTP服务器 HTTPServer ,在这里做个记录
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import urllib.parse
from urllib3 import encode_multipart_formdata
import urllib.parse
import json, re, time
import threading
from http.server import HTTPServer, BaseHTTPRequestHandler, ThreadingHTTPServer
class MyHTTPRequestHandler(BaseHTTPRequestHandler):
timeout = 5
server_version = "Apache" # 设置服务器返回的的响应头
sys_version = ""
protocol_version = 'HTTP/1.1'
# def __init__(self, *args, **kwargs):
# super().__init__(*args, **kwargs)
# self._args = args
# self._kwargs = kwargs
# print(self._args)
# print(self._kwargs)
def do_GET(self):
urlparser = urllib.parse.urlparse(self.path)
print("do_GET", urlparser.path)
# 获取get
get_datas = urllib.parse.parse_qs(urlparser.query, True)
for key in get_datas:
if len(get_datas[key]) == 1:
get_datas[key] = get_datas[key][0]
if urlparser.path.endswith("/list"):
print("get_datas", get_datas)
self.response_msg(json.dumps(get_datas))
def do_POST(self):
urlparser = urllib.parse.urlparse(self.path)
print("do_POST", urlparser.path)
# 获取get
get_datas = urllib.parse.parse_qs(urlparser.query, True)
for key in get_datas:
if len(get_datas[key]) == 1:
get_datas[key] = get_datas[key][0]
# 获取post提交的数据
if (int(self.headers['content-length']) == 0):
post_datas = {}
else:
post_datas = self.rfile.read(int(self.headers['content-length']))
print(self.headers)
print("*" * 50)
# print(post_datas)
if "x-www-form-urlencoded" in self.headers['content-type']:
post_datas = urllib.parse.parse_qs(post_datas.decode(), True)
for key in post_datas:
if len(post_datas[key]) == 1:
post_datas[key] = post_datas[key][0]
elif "multipart/form-data" in self.headers['content-type']:
boundary = self.headers['content-type'].rpartition("boundary=")[2].encode()
result = re.findall(
rb';\s*name=\"(.+?)\"(;\s*filename=\"(.*?)\")?\r\n(Content-Type\:\s*(.*?)\r\n)?\r\n(.*?)\r\n--' + boundary,
post_datas, re.I | re.S)
post_datas = {}
for item in result:
iname = item[0].decode()
if len(item[1]) == 0:
if iname in post_datas:
post_datas[iname].append(item[5].decode())
else:
post_datas[iname] = [item[5].decode()]
else: # 上传文件
filename = item[2].decode()
filetype = item[4].decode() # image/png
open(filename, 'wb').write(item[5])
ivalue = {"filename": filename, "content-type": filetype}
if iname in post_datas:
post_datas[iname].append(ivalue)
else:
post_datas[iname] = [ivalue]
for key in post_datas:
if len(post_datas[key]) == 1:
post_datas[key] = post_datas[key][0]
elif "json" in self.headers['content-type']:
post_datas = json.loads(post_datas.decode())
print("get_datas :", get_datas)
print("post_datas:", post_datas)
if hasattr(self.server, 'externalFunc') and callable(getattr(self.server, 'externalFunc')):
self.server.externalFunc()
self.response_msg(json.dumps(post_datas))
def response_msg(self, message="", code=200):
self.send_response(code)
self.send_header('Pragma', '0')
self.send_header('Expires', 'no-cache')
self.send_header('Content-type', 'text/html; charset=utf-8')
# self.send_header('Content-Length', len(message.encode()))
self.send_header('Connection', 'close')
self.end_headers()
self.wfile.write(message.encode())
def print_currenttime():
print("当前时间: ",time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
def http_server():
host = ('127.0.0.1', 8080)
httpd = HTTPServer(host, MyHTTPRequestHandler)
httpd.externalFunc = print_currenttime
try:
print("Server started on {0[0]},port {0[1]}.....".format(host))
httpd.serve_forever()
except KeyboardInterrupt:
print(" ^C entered, stopping web server...")
httpd.shutdown()
if __name__ == '__main__':
threading.Thread(target=http_server).start()
# try:
# host = ('127.0.0.1', 8080)
# httpd = ThreadingHTTPServer(host, MyHTTPRequestHandler)
# httpd.externalFunc = print_currenttime
# print("Server started on {0[0]},port {0[1]}.....".format(host))
# httpd.serve_forever()
# except KeyboardInterrupt:
# print(" ^C entered, stopping web server...")
# httpd.shutdown()