python伺服器端收發請求的實現代碼_python

來源:互聯網
上載者:User

最近學習了python的一些伺服器端編程,記錄在此。

發送get/post請求

# coding:utf-8import 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':'200'};#與網站構建一個串連conn = httplib.HTTPConnection("localhost:8765");#開始進行資料提交  同時也可以使用get進行conn.request(method="POST",url="/",body=params,headers=headers);#返回處理後的資料response = conn.getresponse();print response.read()#判斷是否提交成功if response.status == 200:  print "發布成功!^_^!";else:  print "發布失敗\^0^/";#關閉串連conn.close();

利用urllib模組可以方便的實現發送http請求.urllib的參考手冊

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

建立http伺服器,處理get,post請求

# 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><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()

注意這裡,python把response的訊息體記錄在了rfile中。BaseHpptServer沒有實現do_POST方法,需要自己重寫。之後我們建立類RequestHandler,繼承自 baseHTTPServer 重寫do_POST方法,讀出rfile的內容即可。
但是要注意,發送端必須指定content-length.若不指定,程式就會卡在rfile.read()上,不知道讀取多少。

參考手冊 http://docs.python.org/2/library/basehttpserver.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.