Python implements an HTTP-based file transfer instance,
This example describes how to implement HTTP-based file transfer in Python. Share it with you for your reference. The specific implementation method is as follows:
I. Problems:
Because I recently read the content of the file transmitted through the POST request and wrote the Server and Client to implement a simple HTTP File Transfer tool.
II. Implementation Code:
Server:
Copy codeThe 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) # file size (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:
Copy codeThe Code is as follows: # 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
I hope this article will help you with Python programming.