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


Posted in Python onSeptember 29, 2014

最近学习了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

Python 相关文章推荐
python with statement 进行文件操作指南
Aug 22 Python
windows系统下Python环境搭建教程
Mar 28 Python
python队列queue模块详解
Apr 27 Python
python 美化输出信息的实例
Oct 15 Python
python redis 删除key脚本的实例
Feb 19 Python
Python3利用print输出带颜色的彩色字体示例代码
Apr 08 Python
pyqt5 从本地选择图片 并显示在label上的实例
Jun 13 Python
python/Matplotlib绘制复变函数图像教程
Nov 21 Python
Python tkinter三种布局实例详解
Jan 06 Python
python re的findall和finditer的区别详解
Nov 15 Python
python实现PolynomialFeatures多项式的方法
Jan 06 Python
Python实现淘宝秒杀功能的示例代码
Jan 19 Python
python利用beautifulSoup实现爬虫
Sep 29 #Python
Python中为feedparser设置超时时间避免堵塞
Sep 28 #Python
跟老齐学Python之从格式化表达式到方法
Sep 28 #Python
跟老齐学Python之print详解
Sep 28 #Python
跟老齐学Python之正规地说一句话
Sep 28 #Python
跟老齐学Python之玩转字符串(2)更新篇
Sep 28 #Python
跟老齐学Python之不要红头文件(2)
Sep 28 #Python
You might like
php关于array_multisort多维数组排序的使用说明
2011/01/04 PHP
PHP实现活动人选抽奖功能
2017/04/19 PHP
javascript 继承实现方法
2009/08/26 Javascript
javascript 设置文本框中焦点的位置
2009/11/20 Javascript
JavaScript Event学习第四章 传统的事件注册模型
2010/02/07 Javascript
JS判断当前日期是否大于某个日期的实现代码
2012/09/02 Javascript
ParseInt函数参数设置介绍
2014/01/02 Javascript
JS使用oumousemove和oumouseout动态改变图片显示的方法
2015/03/31 Javascript
基于JavaScript实现类似于百度学术高级检索功能
2016/03/02 Javascript
jQuery Ajax 全局调用封装实例代码详解
2016/06/02 Javascript
浅谈jquery点击label触发2次的问题
2016/06/12 Javascript
AngularJS开发教程之控制器之间的通信方法分析
2016/12/25 Javascript
详解vue slot插槽的使用方法
2017/06/13 Javascript
mui 打开新窗口的方式总结及注意事项
2017/08/20 Javascript
基于Bootstrap框架菜鸟入门教程(推荐)
2017/09/17 Javascript
jQuery实现中奖播报功能(让文本滚动起来) 简单设置数值即可
2020/03/20 jQuery
Node Express用法详解【安装、使用、路由、中间件、模板引擎等】
2020/05/13 Javascript
JavaScript的垃圾回收机制与内存管理
2020/08/06 Javascript
Python中的自省(反射)详解
2015/06/02 Python
python利用正则表达式排除集合中字符的功能示例
2017/10/10 Python
centos6.8安装python3.7无法import _ssl的解决方法
2018/09/17 Python
Python使用Shelve保存对象方法总结
2019/01/28 Python
简单了解python中的与或非运算
2019/09/18 Python
Python 3.8 新功能大揭秘【新手必学】
2020/02/05 Python
python实现从ftp服务器下载文件
2020/03/03 Python
Python unittest单元测试openpyxl实现过程解析
2020/05/27 Python
python实现移动木板小游戏
2020/10/09 Python
Python3 + Appium + 安卓模拟器实现APP自动化测试并生成测试报告
2021/01/27 Python
英国第二大营养品供应商:Vitabiotics
2016/10/01 全球购物
法人代表任命书范本
2014/06/05 职场文书
领导班子奢靡之风查摆问题及整改措施
2014/09/27 职场文书
2014年纪检监察工作总结
2014/11/11 职场文书
辩论赛开场白大全(主持人+辩手)
2015/05/29 职场文书
鲁滨逊漂流记读书笔记
2015/06/26 职场文书
本地通过nginx配置反向代理的全过程记录
2021/03/31 Servers
Python基础 括号()[]{}的详解
2021/11/07 Python