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 判断自定义对象类型
Mar 21 Python
Sanic框架配置操作分析
Jul 17 Python
Python面向对象总结及类与正则表达式详解
Apr 18 Python
python通过paramiko复制远程文件及文件目录到本地
Apr 30 Python
Python csv文件的读写操作实例详解
Nov 19 Python
使用Python实现画一个中国地图
Nov 23 Python
python将数组n等分的实例
Dec 02 Python
利用Python脚本批量生成SQL语句
Mar 04 Python
Python使用扩展库pywin32实现批量文档打印实例
Apr 09 Python
Python sorted对list和dict排序
Jun 09 Python
使用keras实现非线性回归(两种加激活函数的方式)
Jul 05 Python
浅谈Python爬虫原理与数据抓取
Jul 21 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
mysql limit查询优化分析
2008/11/12 PHP
IIS下PHP连接数据库提示mysql undefined function mysql_connect()
2010/06/04 PHP
解析wamp5下虚拟机配置文档
2013/06/27 PHP
PHP MPDF中文乱码的解决方式
2015/12/08 PHP
PHP中模拟链表和链表的基本操作示例
2016/02/27 PHP
php版微信开发Token验证失败或请求URL超时问题的解决方法
2016/09/23 PHP
Thinkphp3.2实用篇之计算型验证码示例
2017/02/09 PHP
用PHP去掉文件头的Unicode签名(BOM)方法
2017/06/22 PHP
JQuery AJAX 中文乱码问题解决
2013/06/05 Javascript
jQuery中replaceAll()方法用法实例
2015/01/16 Javascript
深入浅析同源策略和跨域访问
2015/11/26 Javascript
jquery实现触发时更新下拉列表内容的方法
2015/12/02 Javascript
Bootstrap Table从服务器加载数据进行显示的实现方法
2016/09/29 Javascript
vue.js中v-on:textInput无法执行事件问题的解决过程
2017/07/12 Javascript
基于JavaScript实现新增内容滚动播放效果附完整代码
2017/08/24 Javascript
Popup弹出框添加数据实现方法
2017/10/27 Javascript
NodeJS 实现多语言的示例代码
2018/09/11 NodeJs
Vue 动态添加路由及生成菜单的方法示例
2019/06/20 Javascript
解决vant title-active-color与title-inactive-color不生效问题
2020/11/03 Javascript
[38:23]完美世界DOTA2联赛循环赛 FTD vs PXG BO2第二场 11.01
2020/11/02 DOTA
Python设计模式之简单工厂模式实例详解
2019/01/22 Python
如何用C代码给Python写扩展库(Cython)
2019/05/17 Python
Python二进制文件读取并转换为浮点数详解
2019/06/25 Python
使用PyCharm官方中文语言包汉化PyCharm
2020/11/18 Python
CSS3 background-image颜色渐变的实现代码
2018/09/13 HTML / CSS
css3边框_动力节点Java学院整理
2017/07/11 HTML / CSS
HTML5移动端手机网站开发流程
2016/04/25 HTML / CSS
Vinatis德国:法国领先的葡萄酒邮购公司
2020/09/07 全球购物
《我不是最弱小的》教学反思
2014/02/23 职场文书
新颖的化妆品活动方案
2014/08/21 职场文书
2014年秘书工作总结
2014/11/25 职场文书
统招统分证明
2015/06/23 职场文书
2019最新劳动仲裁申请书!
2019/07/08 职场文书
SQLServer2019 数据库环境搭建与使用的实现
2021/04/08 SQL Server
Redis三种集群模式详解
2021/10/05 Redis
R9700摩机记
2022/04/05 无线电