SimpleHTTPServer模块详解
SimpleHTTPServer实现文件的展示和下载
可以用python2.7直接启动一个进程。以命令执行的当前目录为页面根目录,如果不存在index.html,默认展示当前目录的所有文件。

python3改动了:python -m http.server 端口号
如果有txt文件就是,可以浏览器页面读取内容,如果是不可读取的文件。那么点击可以直接下载

如果是通过远程连接windows服务器,或者再连接一层。当被限制不能从笔记本本地复制粘贴过去时,可以 使用此方法,xshell上创建这个进程,上传文件,然后在windows远程桌面进行地址访问,来下载文件。
如何实现上传 文件到服务器
当我编辑了index。html文件时,默认展示index.html的内容


wsgiref创建网站

#__*__ encoding:utf-8 _*_
from wsgiref.simple_server import make_server def run_server(environ, start_response): #2)定义执行函数,传参environ, start_response
start_response('200 OK', [('Content-Type', 'text/html;charset=utf8'), ]) # 4) 设置HTTP响应的状态码和头信息start_response('200 OK', [('Content-Type', 'text/html;charset=utf8'), ])
url = environ['PATH_INFO'] #3)取到用户输入的url environ['PATH_INFO']
if url=='/home/':
response=("response:"+url).encode('utf-8')
else:
response = b"404 not found!" #)url满足条件返回内容定义
return [response, ] #6)执行函数返回列表,列表一个元素是返回的内容 if __name__ == '__main__':
httpd = make_server('10.0.0.131', 8090, run_server) #1)make_server 做服务传ip端口和执行函数
httpd.serve_forever() #启动这个服务
程序


参考:https://www.cnblogs.com/machangwei-8/p/11003934.html#_label1_0
SimpleHTTPServer和SocketServer实现index网页访问
官网地址:https://docs.python.org/2/library/simplehttpserver.html

import SimpleHTTPServer
import SocketServer PORT = 9200 Handler = SimpleHTTPServer.SimpleHTTPRequestHandler httpd = SocketServer.TCPServer(("", PORT), Handler) print "serving at port", PORT
httpd.serve_forever()
程序

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="http://10.0.0.131:8000/" method="post">
username:<input type="text" name="username"><br>
password:<input type="password" name="password"><br>
<input type="submit" value="login">
</form>
</body>
</html>
index.html
运行程序。

本机另一个会话访问服务

访问的程序运行当前目录下的 index文件

查看访问情况

现在使用浏览器进行服务的访问,能发现正常访问到index文件的内容

查看浏览器访问情况

SimpleHTTPServer自定义get响应内容

import SimpleHTTPServer
import SocketServer PORT = 9200 class mcwhandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
print "GET"
print self.headers
self.wfile.write('wo shi machangwei')
Handler = mcwhandler httpd = SocketServer.TCPServer(("", PORT), Handler) print "serving at port", PORT
httpd.serve_forever()
程序
import SimpleHTTPServer
import SocketServer PORT = 9200 class mcwhandler(SimpleHTTPServer.SimpleHTTPRequestHandler): #自定义handler类,继承括号里的类
def do_GET(self): #定义get请求方法
print "GET"
print self.headers #headers请求头信息吧
self.wfile.write('wo shi machangwei') #用这个方法来定返回义请求响应内容
Handler = mcwhandler #自定义handler类 httpd = SocketServer.TCPServer(("", PORT), Handler) #传参handler print "serving at port", PORT
httpd.serve_forever()

访问结果:

ie访问:

谷歌访问:

火狐浏览器访问:


# -*- coding: utf-8 -*-
import SimpleHTTPServer
import SocketServer PORT = 9200 class mcwhandler(SimpleHTTPServer.SimpleHTTPRequestHandler): #自定义handler类,继承括号里的类
def createHTML(self):
html = file("index.html", "r")
for line in html:
line.encode(encoding='utf-8')
self.wfile.write(line)
def do_GET(self): #定义get请求方法
print "GET"
self.request
self.responses["Content-type"]="application/json"
print self.headers #headers请求头信息吧
print self.send_head()
self.createHTML() #用这个方法来定返回义请求响应内容
Handler = mcwhandler #自定义handler类 httpd = SocketServer.TCPServer(("", PORT), Handler) #传参handler print "serving at port", PORT
httpd.serve_forever()
程序
get方法里需要调用self.send_head(),浏览器才能将前端页面正常展示

火狐访问打印结果显示

浏览器访问结果

打印具体效果:
def do_GET(self): #定义get请求方法
print "GET"
print "request:============\n",self.request
print "path=============\n",self.path
print "headers:============\n",self.headers #headers请求头信息吧
print "respon:===========\n",self.responses
print "send_head:==============\n"
print self.send_head()
# self.createHTML() #用这个方法来定返回义请求响应内容
self.wfile.write("<h1>mcw</h1>")
[root@mcw1 ~/mcwhttp]$ python mcw4.py
serving at port 9200
GET
request:============
<socket._socketobject object at 0x7f3e24cbac20>
path=============
/
headers:============
Host: 10.0.0.131:9200
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0 respon:===========
{200: ('OK', 'Request fulfilled, document follows'), 201: ('Created', 'Document created, URL follows'), 202: ('Accepted', 'Request accepted, processing continues off-line'), 203: ('Non-Authoritative Information', 'Request fulfilled from cache'), 204: ('No Content', 'Request fulfilled, nothing follows'), 205: ('Reset Content', 'Clear input form for further input.'), 206: ('Partial Content', 'Partial content follows.'), 400: ('Bad Request', 'Bad request syntax or unsupported method'), 401: ('Unauthorized', 'No permission -- see authorization schemes'), 402: ('Payment Required', 'No payment -- see charging schemes'), 403: ('Forbidden', 'Request forbidden -- authorization will not help'), 404: ('Not Found', 'Nothing matches the given URI'), 405: ('Method Not Allowed', 'Specified method is invalid for this resource.'), 406: ('Not Acceptable', 'URI not available in preferred format.'), 407: ('Proxy Authentication Required', 'You must authenticate with this proxy before proceeding.'), 408: ('Request Timeout', 'Request timed out; try again later.'), 409: ('Conflict', 'Request conflict.'), 410: ('Gone', 'URI no longer exists and has been permanently removed.'), 411: ('Length Required', 'Client must specify Content-Length.'), 412: ('Precondition Failed', 'Precondition in headers is false.'), 413: ('Request Entity Too Large', 'Entity is too large.'), 414: ('Request-URI Too Long', 'URI is too long.'), 415: ('Unsupported Media Type', 'Entity body in unsupported format.'), 416: ('Requested Range Not Satisfiable', 'Cannot satisfy request range.'), 417: ('Expectation Failed', 'Expect condition could not be satisfied.'), 100: ('Continue', 'Request received, please continue'), 101: ('Switching Protocols', 'Switching to new protocol; obey Upgrade header'), 300: ('Multiple Choices', 'Object has several resources -- see URI list'), 301: ('Moved Permanently', 'Object moved permanently -- see URI list'), 302: ('Found', 'Object moved temporarily -- see URI list'), 303: ('See Other', 'Object moved -- see Method and URL list'), 304: ('Not Modified', 'Document has not changed since given time'), 305: ('Use Proxy', 'You must use proxy specified in Location to access this resource.'), 307: ('Temporary Redirect', 'Object moved temporarily -- see URI list'), 500: ('Internal Server Error', 'Server got itself in trouble'), 501: ('Not Implemented', 'Server does not support this operation'), 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'), 503: ('Service Unavailable', 'The server cannot process the request due to a high load'), 504: ('Gateway Timeout', 'The gateway server did not receive a timely response'), 505: ('HTTP Version Not Supported', 'Cannot fulfill request.')}
send_head:============== 10.0.0.1 - - [05/Dec/2021 09:13:16] "GET / HTTP/1.1" 200 -
<open file '/root/mcwhttp/index.html', mode 'rb' at 0x7f3e24c63300>
GET
request:============
<socket._socketobject object at 0x7f3e24cbac20>
path=============
/favicon.ico
headers:============
Host: 10.0.0.131:9200
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0
Accept: image/avif,image/webp,*/*
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate
Connection: keep-alive
Referer: http://10.0.0.131:9200/
Cache-Control: max-age=0 respon:===========
{200: ('OK', 'Request fulfilled, document follows'), 201: ('Created', 'Document created, URL follows'), 202: ('Accepted', 'Request accepted, processing continues off-line'), 203: ('Non-Authoritative Information', 'Request fulfilled from cache'), 204: ('No Content', 'Request fulfilled, nothing follows'), 205: ('Reset Content', 'Clear input form for further input.'), 206: ('Partial Content', 'Partial content follows.'), 400: ('Bad Request', 'Bad request syntax or unsupported method'), 401: ('Unauthorized', 'No permission -- see authorization schemes'), 402: ('Payment Required', 'No payment -- see charging schemes'), 403: ('Forbidden', 'Request forbidden -- authorization will not help'), 404: ('Not Found', 'Nothing matches the given URI'), 405: ('Method Not Allowed', 'Specified method is invalid for this resource.'), 406: ('Not Acceptable', 'URI not available in preferred format.'), 407: ('Proxy Authentication Required', 'You must authenticate with this proxy before proceeding.'), 408: ('Request Timeout', 'Request timed out; try again later.'), 409: ('Conflict', 'Request conflict.'), 410: ('Gone', 'URI no longer exists and has been permanently removed.'), 411: ('Length Required', 'Client must specify Content-Length.'), 412: ('Precondition Failed', 'Precondition in headers is false.'), 413: ('Request Entity Too Large', 'Entity is too large.'), 414: ('Request-URI Too Long', 'URI is too long.'), 415: ('Unsupported Media Type', 'Entity body in unsupported format.'), 416: ('Requested Range Not Satisfiable', 'Cannot satisfy request range.'), 417: ('Expectation Failed', 'Expect condition could not be satisfied.'), 100: ('Continue', 'Request received, please continue'), 101: ('Switching Protocols', 'Switching to new protocol; obey Upgrade header'), 300: ('Multiple Choices', 'Object has several resources -- see URI list'), 301: ('Moved Permanently', 'Object moved permanently -- see URI list'), 302: ('Found', 'Object moved temporarily -- see URI list'), 303: ('See Other', 'Object moved -- see Method and URL list'), 304: ('Not Modified', 'Document has not changed since given time'), 305: ('Use Proxy', 'You must use proxy specified in Location to access this resource.'), 307: ('Temporary Redirect', 'Object moved temporarily -- see URI list'), 500: ('Internal Server Error', 'Server got itself in trouble'), 501: ('Not Implemented', 'Server does not support this operation'), 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'), 503: ('Service Unavailable', 'The server cannot process the request due to a high load'), 504: ('Gateway Timeout', 'The gateway server did not receive a timely response'), 505: ('HTTP Version Not Supported', 'Cannot fulfill request.')}
send_head:============== 10.0.0.1 - - [05/Dec/2021 09:13:16] code 404, message File not found
10.0.0.1 - - [05/Dec/2021 09:13:16] "GET /favicon.ico HTTP/1.1" 404 -
None
访问展示

其它信息打印效果
代码:
[root@mcw1 ~/mcwhttp]$ cat mcw4.py
# -*- coding: utf-8 -*-
import SimpleHTTPServer
import SocketServer PORT = 9200 class mcwhandler(SimpleHTTPServer.SimpleHTTPRequestHandler): #自定义handler类,继承括号里的类
def createHTML(self):
html = file("index.html", "r")
for line in html:
line.encode(encoding='utf-8')
self.wfile.write(line)
def do_GET(self): #定义get请求方法
print "一次请求开始===========================\n"
print "GET"
print "path=============\n",self.path
print "send_head:==============\n"
print self.send_head()
print "其它===========\n"
print "address_string:",self.address_string()
print "client_address:",self.client_address
print "date_time_string:",self.date_time_string()
print "error_content_type:",self.error_content_type
print "requestline:",self.requestline
print "raw_requestline",self.raw_requestline
# self.createHTML() #用这个方法来定返回义请求响应内容
self.wfile.write("<h1>mcw</h1>")
Handler = mcwhandler #自定义handler类 httpd = SocketServer.TCPServer(("", PORT), Handler) #传参handler print "serving at port", PORT
httpd.serve_forever() 浏览器访问打印结果:
[root@mcw1 ~/mcwhttp]$ python mcw4.py
serving at port 9200
一次请求开始=========================== GET
path=============
/
send_head:============== 10.0.0.1 - - [05/Dec/2021 09:26:41] "GET / HTTP/1.1" 200 -
<open file '/root/mcwhttp/index.html', mode 'rb' at 0x7f4db3bf1300>
其它=========== address_string: 10.0.0.1
client_address: ('10.0.0.1', 57243)
date_time_string: Sun, 05 Dec 2021 01:27:01 GMT
error_content_type: text/html
requestline: GET / HTTP/1.1
raw_requestline GET / HTTP/1.1 一次请求开始=========================== GET
path=============
/favicon.ico
send_head:============== 10.0.0.1 - - [05/Dec/2021 09:27:02] code 404, message File not found
10.0.0.1 - - [05/Dec/2021 09:27:02] "GET /favicon.ico HTTP/1.1" 404 -
None
其它=========== address_string: 10.0.0.1
client_address: ('10.0.0.1', 61636)
date_time_string: Sun, 05 Dec 2021 01:27:22 GMT
error_content_type: text/html
requestline: GET /favicon.ico HTTP/1.1
raw_requestline GET /favicon.ico HTTP/1.1
由上可知:浏览器上访问,10.0.0.131的9200端口。会先走到vmvare虚拟机的网关10.0.0.1。这里客户端ip也是展示的网关ip10.0.0.1。浏览器一次访问发送了两次请求,一个是请求/ 一个是请求/favicon.ico,这是火狐浏览器的头头部图片
调用就行了,内部实现打印了

post请求

# -*- coding: utf-8 -*-
import SimpleHTTPServer
import SocketServer PORT = 9200 class mcwhandler(SimpleHTTPServer.SimpleHTTPRequestHandler): #自定义handler类,继承括号里的类
def createHTML(self):
html = file("index.html", "r")
for line in html:
line.encode(encoding='utf-8')
self.wfile.write(line)
def do_GET(self): #定义get请求方法
print "一次请求开始===========================\n"
self.send_head()
self.createHTML()
Handler = mcwhandler #自定义handler类 httpd = SocketServer.TCPServer(("", PORT), Handler) #传参handler print "serving at port", PORT
httpd.serve_forever()
程序

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title> Insert title here</title>
</head>
<body>
<form action="http://10.0.0.131:8000/" method="post">
username:<input type="text" name="username"><br>
password:<input type="password" name="password"><br>
<input type="submit" value="login">
</form>
</body>
</html>
index.html
点击请求:

因为后端未实现post请求的函数

添加后端post视图函数

[root@mcw1 ~/mcwhttp]$ cat mcw5.py
# -*- coding: utf-8 -*-
import SimpleHTTPServer
import SocketServer PORT = 9200 class mcwhandler(SimpleHTTPServer.SimpleHTTPRequestHandler): #自定义handler类,继承括号里的类
def createHTML(self):
html = file("index.html", "r")
for line in html:
line.encode(encoding='utf-8')
self.wfile.write(line)
def do_GET(self): #定义get请求方法
print "一次请求开始===========================\n"
self.send_head()
self.createHTML()
def do_POST(self):
print "POST请求开始===================\n"
self.send_head()
self.wfile.write('''<html>
<head>
<meta charset="UTF-8"></head>
<body>
<div style="color:red;"><h1 charset="ISO-8859-1">post请求返回的页面</h1></div>
</body>
</html>''')
Handler = mcwhandler #自定义handler类 httpd = SocketServer.TCPServer(("", PORT), Handler) #传参handler print "serving at port", PORT
httpd.serve_forever()
post视图函数

[root@mcw1 ~/mcwhttp]$ cat index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title> Insert title here</title>
</head>
<body>
<form action="" method="post">
username:<input type="text" name="username"><br>
password:<input type="password" name="password"><br>
<input type="submit" value="login">
</form>
</body>
</html>
前端代码
get请求,输入内容,点击登录


点击登录,成功返回内容


后面就可以根据path自己写路由(url),写html模块,自己定义替换语言。数据库可以用Excel来实现,使用txt文本来实现等等。
两个模块,一个提供tcp网络编程,一个实现将http请求作为tcp网络编程的参数传进去做处理
获取请求的数据
length = int(self.headers.getheader('content-length'))
qs = self.rfile.read(length)

# -*- coding: utf-8 -*-
import SimpleHTTPServer
import SocketServer PORT = 9200 class mcwhandler(SimpleHTTPServer.SimpleHTTPRequestHandler): #自定义handler类,继承括号里的类
def createHTML(self):
html = file("index.html", "r")
for line in html:
line.encode(encoding='utf-8')
self.wfile.write(line)
def do_GET(self): #定义get请求方法
print "一次请求开始===========================\n"
self.send_head()
self.createHTML()
def do_POST(self):
print "POST请求开始===================\n"
self.send_head()
length = int(self.headers.getheader('content-length'))
qs = self.rfile.read(length)
print "====================\npost 请求的数据内容: %s"%qs
self.wfile.write('''<html>
<head>
<meta charset="UTF-8"></head>
<body>
<div style="color:red;"><h1 charset="ISO-8859-1">post请求返回的页面</h1></div>
</body>
</html>''')
Handler = mcwhandler #自定义handler类 httpd = SocketServer.TCPServer(("", PORT), Handler) #传参handler print "serving at port", PORT
httpd.serve_forever()
程序

查看请求头信息 dir
headers: [
'Host: 10.0.0.131:9200\r\n',
'User-Agent: Mozilla/5.0 (Windows NT 10.0;
Win64; x64; rv:94.0) Gecko/20100101
Firefox/94.0\r\n',
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\r\n',
'Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2\r\n',
'Accept-Encoding: gzip, deflate\r\n',
'Connection: keep-alive\r\n',
'Upgrade-Insecure-Requests: 1\r\n']
=======
dict: {
'accept-language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
'accept-encoding': 'gzip, deflate',
'host': '10.0.0.131:9200',
'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,
image/avif,image/webp,*/*;q=0.8',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0',
'connection': 'keep-alive',
'upgrade-insecure-requests': '1'} items(): [
('origin', 'http://10.0.0.131:9200'),
('content-length', '35'),
('accept-language', 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2'),
('accept-encoding', 'gzip, deflate'),
('connection', 'keep-alive'),
('accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8'),
('user-agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0'),
('host', '10.0.0.131:9200'),
('referer', 'http://10.0.0.131:9200/'),
('upgrade-insecure-requests', '1'),
('content-type', 'application/x-www-form-urlencoded')]
=======
keys(): ['origin', 'content-length', 'accept-language', 'accept-encoding', 'connection',
'accept', 'user-agent', 'host', 'referer',
'upgrade-insecure-requests', 'content-type']
=======
values(): ['http://10.0.0.131:9200', '35', 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
'gzip, deflate', 'keep-alive',
'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0',
'10.0.0.131:9200', 'http://10.0.0.131:9200/',
'1', 'application/x-www-form-urlencoded'] =====================
headers 的dir: ['__contains__', '__delitem__', '__doc__', '__getitem__', '__init__',
'__iter__', '__len__', '__module__',
'__setitem__', '__str__', 'dict', 'encodingheader', 'fp', 'get', 'getaddr', 'getaddrlist',
'getallmatchingheaders', 'getdate',
'getdate_tz', 'getencoding', 'getfirstmatchingheader', 'getheader', 'getheaders', 'getmaintype',
'getparam', 'getparamnames',
'getplist', 'getrawheader', 'getsubtype', 'gettype', 'has_key', 'headers', 'iscomment',
'isheader', 'islast', 'items', 'keys',
'maintype', 'parseplist', 'parsetype', 'plist', 'plisttext', 'readheaders',
'rewindbody', 'seekable', 'setdefault', 'startofbody',
'startofheaders', 'status', 'subtype', 'type', 'typeheader', 'unixfrom', 'values']

# -*- coding: utf-8 -*-
import SimpleHTTPServer
import SocketServer PORT = 9200 class mcwhandler(SimpleHTTPServer.SimpleHTTPRequestHandler): #自定义handler类,继承括号里的类
def createHTML(self):
html = file("index.html", "r")
for line in html:
line.encode(encoding='utf-8')
self.wfile.write(line)
def do_GET(self): #定义get请求方法
print "一次请求开始===========================\n"
self.send_head()
self.createHTML()
def do_POST(self):
print "POST请求开始===================\n"
self.send_head()
length = int(self.headers.getheader('content-length'))
print "============\nlength: ",self.headers.getheader('content-length')
qs = self.rfile.read(length)
print "====================\npost 请求的数据内容: %s"%qs
print "=====================\nheaders 的dir:",dir(self.headers)
self.wfile.write('''<html>
<head>
<meta charset="UTF-8"></head>
<body>
<div style="color:red;"><h1 charset="ISO-8859-1">post请求返回的页面</h1></div>
</body>
</html>''')
Handler = mcwhandler #自定义handler类 httpd = SocketServer.TCPServer(("", PORT), Handler) #传参handler print "serving at port", PORT
httpd.serve_forever()
程序
视图函数:
def do_POST(self):
print "POST请求开始===================\n"
self.send_head()
length = int(self.headers.getheader('content-length'))
print "============\nlength: ",self.headers.getheader('content-length')
qs = self.rfile.read(length)
print "====================\npost 请求的数据内容: %s"%qs
print "=====================\nheaders 的dir:",dir(self.headers)
self.wfile.write('''<html>
<head>
<meta charset="UTF-8"></head>
<body>
<div style="color:red;"><h1 charset="ISO-8859-1">post请求返回的页面</h1></div>
</body>
</html>''') 结果:
[root@mcw1 ~/mcwhttp]$ python mcw5.py
serving at port 9200
一次请求开始=========================== 10.0.0.1 - - [05/Dec/2021 11:07:16] "GET / HTTP/1.1" 200 -
一次请求开始=========================== 10.0.0.1 - - [05/Dec/2021 11:07:16] "GET /favicon.ico HTTP/1.1" 200 -
POST请求开始=================== 10.0.0.1 - - [05/Dec/2021 11:07:22] "POST / HTTP/1.1" 200 -
============
length: 35
====================
post 请求的数据内容: username=machangwei&password=123456
=====================
headers 的dir: ['__contains__', '__delitem__', '__doc__', '__getitem__', '__init__', '__iter__', '__len__', '__module__', '__setitem__', '__str__', 'dict', 'encodingheader', 'fp', 'get', 'getaddr', 'getaddrlist', 'getallmatchingheaders', 'getdate', 'getdate_tz', 'getencoding', 'getfirstmatchingheader', 'getheader', 'getheaders', 'getmaintype', 'getparam', 'getparamnames', 'getplist', 'getrawheader', 'getsubtype', 'gettype', 'has_key', 'headers', 'iscomment', 'isheader', 'islast', 'items', 'keys', 'maintype', 'parseplist', 'parsetype', 'plist', 'plisttext', 'readheaders', 'rewindbody', 'seekable', 'setdefault', 'startofbody', 'startofheaders', 'status', 'subtype', 'type', 'typeheader', 'unixfrom', 'values']
一次请求开始=========================== 10.0.0.1 - - [05/Dec/2021 11:07:22] "GET /favicon.ico HTTP/1.1" 200 -
# -*- coding: utf-8 -*-
import SimpleHTTPServer
import SocketServer PORT = 9200 class mcwhandler(SimpleHTTPServer.SimpleHTTPRequestHandler): # 自定义handler类,继承括号里的类
def createHTML(self):
html = file("index.html", "r")
for line in html:
line.encode(encoding='utf-8')
self.wfile.write(line) def do_GET(self): # 定义get请求方法
print "一次请求开始===========================\n"
self.send_head()
if self.path=="/":
print "=======\nget():", self.headers.get('mcw')
print "=======\nstatus:", self.headers.status
print "=======\ntype:", self.headers.type
print "=======\nheaders:", self.headers.headers
print "=======\ndict:", self.headers.dict
print "=======\nencodingheader:", self.headers.encodingheader
print "=======\ngetaddr():", self.headers.getaddr('host')
print "=======\ngetaddrlist():", self.headers.getaddrlist('host')
print "=======\ngetfirstmatchingheader():", self.headers.getfirstmatchingheader('host')
print "=======\nfp:", self.headers.fp
print "=======\ngetallmatchingheaders():", self.headers.getallmatchingheaders('host')
print "=======\ngetdate():", self.headers.getdate('host')
print "=======\ngetdate_tz():", self.headers.getdate_tz('host')
print "=======\ngetrawheader():", self.headers.getrawheader('host')
print "=======\ngetplist():", self.headers.getplist()
print "=======\ngetmaintype():", self.headers.getmaintype()
print "=======\ngetheader():", self.headers.getheader('host')
print "=======\ngetparam():", self.headers.getparam("mcw")
print "=======\ngetparamnames():", self.headers.getparamnames()
print "=======\nparseplist():", self.headers.parseplist()
print "=======\ngettype():", self.headers.gettype()
#print "=======\nreadheaders():", self.headers.readheaders()
print "=======\nunixfrom:", self.headers.unixfrom
print "=======\nstartofbody:", self.headers.startofbody
print "=======\nplist:", self.headers.plist
print "=======\nplisttext:", self.headers.plisttext self.createHTML() def do_POST(self):
aa=self.send_head()
if self.path=="/":
print "POST请求开始===================\n"
print "=======\nitems():", self.headers.items()
print "=======\nkeys():", self.headers.keys()
print "=======\nvalues():", self.headers.values()
print "=======\ngetparam():", self.headers.getparam('username')
print "=======\ngetparamnames():", self.headers.getparamnames()
print "=======\nparseplist():", self.headers.parseplist()
length = int(self.headers.getheader('content-length'))
print "============\n请求的数据内容长度getheader('content-length'): ", self.headers.getheader('content-length')
qs = self.rfile.read(length)
print "====================\npost 请求的数据内容self.rfile.read(length): %s" % qs
print "=====================\nheaders 的dir:", dir(self.headers)
print "==================\nself.send_head()返回内容:",aa
self.wfile.write('''<html>
<head>
<meta charset="UTF-8"></head>
<body>
<div style="color:red;"><h1 charset="ISO-8859-1">post请求返回的页面</h1></div>
</body>
</html>''') Handler = mcwhandler # 自定义handler类 httpd = SocketServer.TCPServer(("", PORT), Handler) # 传参handler print "serving at port", PORT
httpd.serve_forever()
执行结果:
[root@mcw1 ~/mcwhttp]$ python mcw6.py
serving at port 9200
一次请求开始=========================== 10.0.0.1 - - [05/Dec/2021 12:05:15] "GET / HTTP/1.1" 200 -
=======
get(): None
=======
status:
=======
type: text/plain
=======
headers: ['Host: 10.0.0.131:9200\r\n', 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0\r\n', 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8\r\n', 'Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2\r\n', 'Accept-Encoding: gzip, deflate\r\n', 'Connection: keep-alive\r\n', 'Upgrade-Insecure-Requests: 1\r\n']
=======
dict: {'accept-language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2', 'accept-encoding': 'gzip, deflate', 'host': '10.0.0.131:9200', 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0', 'connection': 'keep-alive', 'upgrade-insecure-requests': '1'}
=======
encodingheader: None
=======
getaddr(): ('', '9200')
=======
getaddrlist(): [('', '9200')]
=======
getfirstmatchingheader(): ['Host: 10.0.0.131:9200\r\n']
=======
fp: <socket._fileobject object at 0x7fb84a902450>
=======
getallmatchingheaders(): ['Host: 10.0.0.131:9200\r\n']
=======
getdate(): None
=======
getdate_tz(): None
=======
getrawheader(): 10.0.0.131:9200 =======
getplist(): []
=======
getmaintype(): text
=======
getheader(): 10.0.0.131:9200
=======
getparam(): None
=======
getparamnames(): []
=======
parseplist(): None
=======
gettype(): text/plain
=======
unixfrom:
=======
startofbody: None
=======
plist: []
=======
plisttext:
一次请求开始=========================== 10.0.0.1 - - [05/Dec/2021 12:05:15] "GET /favicon.ico HTTP/1.1" 200 -
10.0.0.1 - - [05/Dec/2021 12:05:20] "POST / HTTP/1.1" 200 -
POST请求开始=================== =======
items(): [('origin', 'http://10.0.0.131:9200'), ('content-length', '35'), ('accept-language', 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2'), ('accept-encoding', 'gzip, deflate'), ('connection', 'keep-alive'), ('accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8'), ('user-agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0'), ('host', '10.0.0.131:9200'), ('referer', 'http://10.0.0.131:9200/'), ('upgrade-insecure-requests', '1'), ('content-type', 'application/x-www-form-urlencoded')]
=======
keys(): ['origin', 'content-length', 'accept-language', 'accept-encoding', 'connection', 'accept', 'user-agent', 'host', 'referer', 'upgrade-insecure-requests', 'content-type']
=======
values(): ['http://10.0.0.131:9200', '35', 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2', 'gzip, deflate', 'keep-alive', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:94.0) Gecko/20100101 Firefox/94.0', '10.0.0.131:9200', 'http://10.0.0.131:9200/', '1', 'application/x-www-form-urlencoded']
=======
getparam(): None
=======
getparamnames(): []
=======
parseplist(): None
============
请求的数据内容长度getheader('content-length'): 35
====================
post 请求的数据内容self.rfile.read(length): username=machangwei&password=123456
=====================
headers 的dir: ['__contains__', '__delitem__', '__doc__', '__getitem__', '__init__', '__iter__', '__len__', '__module__', '__setitem__', '__str__', 'dict', 'encodingheader', 'fp', 'get', 'getaddr', 'getaddrlist', 'getallmatchingheaders', 'getdate', 'getdate_tz', 'getencoding', 'getfirstmatchingheader', 'getheader', 'getheaders', 'getmaintype', 'getparam', 'getparamnames', 'getplist', 'getrawheader', 'getsubtype', 'gettype', 'has_key', 'headers', 'iscomment', 'isheader', 'islast', 'items', 'keys', 'maintype', 'parseplist', 'parsetype', 'plist', 'plisttext', 'readheaders', 'rewindbody', 'seekable', 'setdefault', 'startofbody', 'startofheaders', 'status', 'subtype', 'type', 'typeheader', 'unixfrom', 'values']
==================
self.send_head()返回内容: <open file '/root/mcwhttp/index.html', mode 'rb' at 0x12d7300>
一次请求开始=========================== 10.0.0.1 - - [05/Dec/2021 12:05:21] "GET /favicon.ico HTTP/1.1" 200 -

[root@mcw1 ~/mcwhttp]$ cat runtest.py
import SimpleHTTPServer
import SocketServer
import re def htc(m):
return chr(int(m.group(1), 16)) def urldecode(url):
rex = re.compile('%([0-9a-hA-H][0-9a-hA-H])', re.M)
return rex.sub(htc, url) class SETHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def createHTML(self):
html = file("index.html", "r")
for line in html:
self.wfile.write(line) def do_GET(self):
print "GET"
print self.headers
self.createHTML() def do_POST(self):
print "POST"
print self.headers
length = int(self.headers.getheader('content-length'))
qs = self.rfile.read(length)
url = urldecode(qs)
print "url="
print url
self.createHTML() Handler = SETHandler
PORT = 8000
httpd = SocketServer.TCPServer(('0.0.0.0', PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
可参考程序

mcwstr2='''-----------------------------15257289834991275059027017
Content-Disposition: form-data; name="upload"; filename="mcw1.txt"
Content-Type: text/plainsssssssss at sun.reflect.GeneratedMethodAccessor177.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) -----------------------------15257289834991275059027017--
''' import re
# ret2 = re.search('.*Content-Type:(?P<mcw2>.*).*(?P<mcw3>a.*)',mcwstr2[56:]) str_len=len(mcwstr2)
li=mcwstr2.splitlines()
li_len=len(li)
start_len=0
end_len=0
for i in range(li_len):
if i in [0,1,2,3]:
start_len=start_len+len(li[i])
if i in [li_len-1,li_len-2]:
end_len=end_len+len(li[i])
my_start=start_len+1+3
my_end=str_len-end_len
my_str=mcwstr2[my_start:my_end]
# print mcwstr2[158:374-61]
print len(li),str_len,start_len,end_len,"\n",my_str,
某次調試
参考链接:https://www.jb51.net/article/65453.htm
上传参考:https://www.cnblogs.com/fatt/p/6722419.html
SimpleHTTPServer模块详解的更多相关文章
- Python中操作mysql的pymysql模块详解
Python中操作mysql的pymysql模块详解 前言 pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同.但目前pymysql支持python3.x而后者不支持 ...
- python之OS模块详解
python之OS模块详解 ^_^,步入第二个模块世界----->OS 常见函数列表 os.sep:取代操作系统特定的路径分隔符 os.name:指示你正在使用的工作平台.比如对于Windows ...
- python之sys模块详解
python之sys模块详解 sys模块功能多,我们这里介绍一些比较实用的功能,相信你会喜欢的,和我一起走进python的模块吧! sys模块的常见函数列表 sys.argv: 实现从程序外部向程序传 ...
- python中threading模块详解(一)
python中threading模块详解(一) 来源 http://blog.chinaunix.net/uid-27571599-id-3484048.html threading提供了一个比thr ...
- python time 模块详解
Python中time模块详解 发表于2011年5月5日 12:58 a.m. 位于分类我爱Python 在平常的代码中,我们常常需要与时间打交道.在Python中,与时间处理有关的模块就包括: ...
- python time模块详解
python time模块详解 转自:http://blog.csdn.net/kiki113/article/details/4033017 python 的内嵌time模板翻译及说明 一.简介 ...
- 小白的Python之路 day5 time,datatime模块详解
一.模块的分类 可以分成三大类: 1.标准库 2.开源模块 3.自定义模块 二.标准库模块详解 1.time与datetime 在Python中,通常有这几种方式来表示时间:1)时间戳 2)格式化的时 ...
- 小白的Python之路 day5 random模块和string模块详解
random模块详解 一.概述 首先我们看到这个单词是随机的意思,他在python中的主要用于一些随机数,或者需要写一些随机数的代码,下面我们就来整理他的一些用法 二.常用方法 1. random.r ...
- Python中time模块详解
Python中time模块详解 在平常的代码中,我们常常需要与时间打交道.在Python中,与时间处理有关的模块就包括:time,datetime以及calendar.这篇文章,主要讲解time模块. ...
- Ansible安装部署及常用模块详解
Ansible命令使用 Ansible语法使用ansible <pattern_goes_here> -m <module_name> -a <arguments> ...
随机推荐
- docker 应用篇————docker-compose[十九]
前言 简单介绍一下docker compose. 正文 首先进行下载一下. sudo curl -L "https://github.com/docker/compose/releases/ ...
- Bogus 实战:使用 Bogus 和 EFCore 生成模拟数据和种子数据【完整教程】
引言 上一章我们介绍了在xUnit单元测试中用xUnit.DependencyInject来使用依赖注入,上一章我们的Sample.Repository仓储层有一个批量注入的接口没有做单元测试,今天用 ...
- 使用ollama分别在我的window、mac、小米手机上部署体验llama3-8b
1.ollama到底是个什么玩意 一句话来说, Ollama 是一个基于 Go 语言开发的简单易用的本地大模型运行框架.可以将其类比为 docker(有类似docker中的一些常规命令list,pul ...
- JVM简明笔记4:垃圾回收
1 垃圾回收相关算法 垃圾回收器首先要做的就是,判断一个对象是存活状态还是死亡状态,死亡的对象将会被标识为垃圾数据并等待收集器进行清除. 判断一个对象是否为死亡状态的常用算法有两个:引用计数器算法 . ...
- 用积木讲运维,这样的IT人太会了
简介: 日志服务SLS提供数据采集.加工.分析.告警可视化与投递功能,为AIOps.大数据分析.运营服务.大数据安全等场景提供支撑,并能以搭积木的方式适配各类运维场景,辅助企业的IT决策.近日,日志服 ...
- 【ESSD技术解读-01】 云原生时代,阿里云块存储 ESSD 快照服务如何被企业级数据保护所集成?
简介: 本文描述了阿里云块存储快照服务基于高性能 ESSD 云盘提升快照服务性能,提供轻量.实时的用户体验及揭秘背后的技术原理.依据行业发展及云上数据保护场景,为企业用户及备份厂商提供基于快照高级特 ...
- 深入理解云计算OpenAPI体系
简介: 就云计算的API来看,当前并没有类似POSIX这样的API标准,基本上各大厂商各自为政.当然,有一些业界主流标准例如OAS获得多数云厂商的支持,但云厂商本身的API却往往由于历史原因.技术路 ...
- [FAQ] edge debug栏的网络里 没有见到 All Fetch/XHR JS CSS 这些东西
一种方式是 打开调试器的设置,重置默认并刷新即可. 另一种方式是把这个 "筛选" 点掉. Tool:揭开网站所用的技术 Link:https://www.cnblogs.com ...
- [FE] FastAdmin 动态下拉组件 Selectpage 自定义 data-params
正常情况下,我们想获取列表只需要定义接口路径和要显示的字段名即可, 比如: <input id="c-package_ids" data-rule="require ...
- [FAQ] Jetbrains 官网不能访问,获取 Goland 的下载地址
2020.02 安装包下载 Link:https://www.cnblogs.com/farwish/p/14186441.html