ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

SimpleHTTPServer模块详解

2021-12-20 19:00:11  阅读:285  来源: 互联网

标签:__ 10.0 SimpleHTTPServer self html headers 详解 模块 print


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

标签:__,10.0,SimpleHTTPServer,self,html,headers,详解,模块,print
来源: https://www.cnblogs.com/machangwei-8/p/15643121.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有