Python server-side request sending and receiving implementation code, python server-side
I recently learned some server-side programming of python, which is recorded here.
Send get/post requests
# Coding: utf-8import httplib, urllib # Load Module # urllib can open the website to get # res = urllib. urlopen ('HTTP: // baidu.com '); # print res. headers # define the data params to be sent = urllib. urlencode ({'param': '6'}); # defines some file headers = {"Content-Type": "application/x-www-form-urlencoded ", "Connection": "Keep-Alive", 'content-length': '000000'}; # Build a Connection with the website. conn = httplib. HTTPConnection ("localhost: 8765"); # You can use get to start data submission. request (method = "POST", ur L = "/", body = params, headers = headers); # Return the processed data response = conn. getresponse (); print response. read () # determine whether the submission is successful if response. status = 200: print "published successfully! ^_^! "; Else: print" publishing failed \ ^ 0 ^/"; # close connection conn. close ();
Use the urllib module to conveniently send http request. urllib Reference Manual
Http://docs.python.org/2/library/urllib.html
Create an http server to process get and post requests
# coding:utf-8from BaseHTTPServer import HTTPServer,BaseHTTPRequestHandlerclass RequestHandler(BaseHTTPRequestHandler): def _writeheaders(self): print self.path print self.headers self.send_response(200); self.send_header('Content-type','text/html'); self.end_headers() def do_Head(self): self._writeheaders() def do_GET(self): self._writeheaders() self.wfile.write("""<!DOCTYPE HTML>
Note that python records the response Message Body in rfile. BaseHpptServer does not implement the do_POST method and needs to be rewritten by itself. Then we will create a new RequestHandler class, inherit from baseHTTPServer to override the do_POST method, and read the rfile content.
However, the sender must specify content-length. If this parameter is not specified, the program will be stuck on rfile. read () and will not know how much it will read.
Reference manual http://docs.python.org/2/library/basehttpserver.html
How does python receive a zip package returned by http?
Response is an HTTPResponse Objects, and read is the object content.
Data = response. read ()
F = open (r 'C: \ XX.zip ', 'wb ')
F. write (data)
F. close ()
Python Server File
Er... Please re-describe the problem. Is the content in a.txt extracted? Can you open a.txt now? Is a line break between two teams?