Python server-side transceiver request implementation code _python

Source: Internet
Author: User

Recently learned some of Python's server-side programming, recorded here.

Send Get/post Request

# coding:utf-8
Import httplib,urllib #加载模块
#urllib可以打开网站去拿
#res = Urllib.urlopen (' http://baidu.com ');
#print res.headers
#定义需要进行发送的数据   
params = urllib.urlencode ({' param ': ' 6 '});
#定义一些文件头   
headers = {"Content-type": "application/x-www-form-urlencoded",
      "Connection": "Keep-alive", ' Content-length ': ';
#与网站构建一个连接
conn = httplib. Httpconnection ("localhost:8765");
#开始进行数据提交  can also use get for
conn.request (method= "POST", url= "/", body=params,headers=headers);
#返回处理后的数据
response = Conn.getresponse ();
Print Response.read ()
#判断是否提交成功
If response.status =
  print "published successfully! ^_^!";
else:
  print "Publish failed \^0^/";
#关闭连接
conn.close ();

The Urllib module can be used to send HTTP requests conveniently. URLLIB Reference Manual

Http://docs.python.org/2/library/urllib.html

Establish HTTP server, process get,post request

# 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.wfi Le.write ("" "<! DOCTYPE html>  

Note that Python records the response message body in the rfile. Basehpptserver does not implement the Do_post method and needs to rewrite it yourself. Then we create a new class RequestHandler, inherit from Basehttpserver rewrite Do_post method, read out rfile content.
Note, however, that the sender must specify the content-length. If not specified, the program will be stuck on the Rfile.read (), do not know how much read.

Reference manual Http://docs.python.org/2/library/basehttpserver.html

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.