python服务器端收发请求的实现代码

yipeiwu_com4年前服务器

最近学习了python的一些服务器端编程,记录在此。

发送get/post请求

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

注意这里,python把response的消息体记录在了rfile中。BaseHpptServer没有实现do_POST方法,需要自己重写。之后我们新建类RequestHandler,继承自 baseHTTPServer 重写do_POST方法,读出rfile的内容即可。
但是要注意,发送端必须指定content-length.若不指定,程序就会卡在rfile.read()上,不知道读取多少。

参考手册 http://docs.python.org/2/library/basehttpserver.html

相关文章

使用Django搭建web服务器的例子(最最正确的方式)

使用Django搭建web服务器的例子(最最正确的方式)

今晚在Mac OS中搭建web服务器时遇到一点冲突,逛了几个论坛和网站,都说的太片面。 先列出最正确的搭建步骤:(无论你是任何操作系统,或者任何版本,都没毛病) ① 随便找个位置建一个文...

php获取服务器端mac和客户端mac的地址支持WIN/LINUX

获取服务器mac 复制代码 代码如下: <?php /** 获取网卡的MAC地址原码;目前支持WIN/LINUX系统 获取机器网卡的物理(MAC)地址 **/ class Getm...

php实现Linux服务器木马排查及加固功能

网站频繁被挂马?做一些改进,基本上能把这个问题解决,因为discuz x等程序存在漏洞,被上传了websehll,每次被删除过段时间又出来了,最终查到所有的木马。 从以下几个方...

Python使用Paramiko模块编写脚本进行远程服务器操作

简介: paramiko是python(2.2或更高)的模块,遵循SSH2协议实现了安全(加密和认证)连接远程机器。 安装所需软件包: http://ftp.dlitz.net/pub/...

php集成套件服务器xampp安装使用教程(适合第一次玩PHP的新手)

php集成套件服务器xampp安装使用教程(适合第一次玩PHP的新手)

环境搭建 软件: xampp   下载地址:https://www.apachefriends.org/zh_cn/index.html (建议使用迅雷下载,不然速度...