Python implementation based on HTTP file transfer instance _python

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.