本文執行個體講述了Python實現基於HTTP檔案傳輸的方法。分享給大家供大家參考。具體實現方法如下:
一、問題:
因為需要最近看了一下通過POST請求傳輸檔案的內容 並且自己寫了Server和Client實現了一個簡單的機遇HTTP的檔案傳輸工具
二、實現代碼:
Server端:
代碼如下:
#coding=utf-8
from BaseHTTPServer import BaseHTTPRequestHandler
import cgi
class PostHandler(BaseHTTPRequestHandler):
def do_POST(self):
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
}
)
self.send_response(200)
self.end_headers()
self.wfile.write('Client: %sn ' % str(self.client_address) )
self.wfile.write('User-agent: %sn' % str(self.headers['user-agent']))
self.wfile.write('Path: %sn'%self.path)
self.wfile.write('Form data:n')
for field in form.keys():
field_item = form[field]
filename = field_item.filename
filevalue = field_item.value
filesize = len(filevalue)#檔案大小(位元組)
print len(filevalue)
with open(filename.decode('utf-8')+'a','wb') as f:
f.write(filevalue)
return
if __name__=='__main__':
from BaseHTTPServer import HTTPServer
sever = HTTPServer(('localhost',8080),PostHandler)
print 'Starting server, use to stop'
sever.serve_forever()
Client端:
代碼如下:
#coding=utf-8
import requests
url = 'http://localhost:8080'
path = u'D:快盤阿狸頭像.jpg'
print path
files = {'file': open(path, 'rb')}
r = requests.post(url, files=files)
print r.url,r.text
希望本文所述對大家的Python程式設計有所協助。