The examples in this article describe how Python implements HTTP file-based transfer. Share to everyone for your reference. The implementation method is as follows:
First, the question:
Because I need to look at it recently. Transferring the contents of a file via a POST request and writing it yourself server and client implement a simple Opportunity HTTP file Transfer tool
Second, the implementation of code:
Server side:
The code is 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 To stop '
Sever.serve_forever ()
Client side:
The code is as follows:
#coding =utf-8
Import requests
url = ' http://localhost:8080 '
Path = U ' D: Fast disk ali avatar. jpg '
Print path
Files = {' file ': Open (Path, ' RB ')}
r = Requests.post (URL, files=files)
Print R.url,r.text
Hopefully this article will help you with Python programming.