Python server side send and receive the request implementation code

  • 2020-04-02 14:13:07
  • OfStack

I recently learned some server-side programming in python, note here.

Send a get/post request


# coding:utf-8
import httplib,urllib # Load module 
#urllib You can go to the website and get it 
#res = urllib.urlopen('http://baidu.com');
#print res.headers
# Define the data that needs to be sent    
params = urllib.urlencode({'param':'6'});
# Define some file headers    
headers = {"Content-Type":"application/x-www-form-urlencoded",
      "Connection":"Keep-Alive",'Content-length':'200'};
# Build a connection to the site 
conn = httplib.HTTPConnection("localhost:8765");
# Start the data submission    It can also be used get for 
conn.request(method="POST",url="/",body=params,headers=headers);
# Returns the processed data 
response = conn.getresponse();
print response.read()
# Determine whether the submission was successful 
if response.status == 200:
  print " Release success !^_^!";
else:
  print " Post failure ^0^/";
# Close the connection 
conn.close();

Using urllib module can be convenient to send HTTP requests. Urllib reference manual

(link: http://docs.python.org/2/library/urllib.html)

Set up an HTTP server to handle get and post requests


# coding:utf-8
from BaseHTTPServer import HTTPServer,BaseHTTPRequestHandler
class 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>
<html lang="en-US">
<head>
	<meta charset="UTF-8">
	<title></title>
</head>
<body>
<p>this is get!</p>
</body>
</html>"""+str(self.headers))
  def do_POST(self):
    self._writeheaders()
    length = self.headers.getheader('content-length');
    nbytes = int(length)
    data = self.rfile.read(nbytes)
    self.wfile.write("""<!DOCTYPE HTML>
<html lang="en-US">
<head>
	<meta charset="UTF-8">
	<title></title>
</head>
<body>
<p>this is put!</p>
</body>
</html>"""+str(self.headers)+str(self.command)+str(self.headers.dict)+data)
addr = ('',8765)
server = HTTPServer(addr,RequestHandler)
server.serve_forever()

Note here that python records the body of the response message in rfile. BaseHpptServer does not implement the do_POST method and needs to be rewritten by itself. We then create a new class, RequestHandler, inherit from baseHTTPServer and override the do_POST method to read the contents of the rfile.
Note, however, that the sender must specify content-length. If you don't, the program will get stuck on rfile.read(), not knowing how much to read.

Reference manual (link: http://docs.python.org/2/library/basehttpserver.html)


Related articles: