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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM