The example in this article describes Python's implementation of HTTP file transfer methods. Share to everyone for your reference. The implementation methods are as follows:
First, the question:
Because you need to take a look at the contents of the transfer file over a POST request and write it yourself server and client implement a simple Opportunity HTTP file Transfer tool
Second, the implementation code:
Server End:
Copy Code code as follows:
#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) #文件大小 (bytes)
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 <Ctrl-C> to stop '
Sever.serve_forever ()
Client side:
Copy Code code as follows:
#coding =utf-8
Import requests
url = ' http://localhost:8080 '
Path = U ' D: Quick dial ali avatar. jpg '
Print path
Files = {' file ': Open (Path, ' RB ')}
r = Requests.post (URL, files=files)
Print R.url,r.text
I hope this article will help you with your Python programming.