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 拆包可迭代数据如tuple, list
Dec 29 Python
python实现百万答题自动百度搜索答案
Jan 16 Python
解决Python selenium get页面很慢时的问题
Jan 30 Python
学Python 3的理由和必要性
Nov 19 Python
tensorflow mnist 数据加载实现并画图效果
Feb 05 Python
Python3 Tensorlfow:增加或者减小矩阵维度的实现
May 22 Python
django haystack实现全文检索的示例代码
Jun 24 Python
大数据分析用java还是Python
Jul 06 Python
python利用faker库批量生成测试数据
Oct 15 Python
Django自带的用户验证系统实现
Dec 18 Python
一文搞懂python异常处理、模块与包
Jun 26 Python
Python matplotlib绘制雷达图
Apr 13 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
greybox——不开新窗口看新的网页
2007/02/20 Javascript
仿服务器端脚本方式的JS模板实现方法
2007/04/27 Javascript
javascript 避免闭包引发的问题
2009/03/17 Javascript
Jquery Ajax学习实例4 向WebService发出请求,返回实体对象的异步调用
2010/03/16 Javascript
使用Jquery来实现可以输入值的下拉选单 雏型
2011/12/06 Javascript
Google 地图叠加层实例讲解
2016/08/06 Javascript
JS实现简单的选择题测评系统代码思路详解(demo)
2017/09/03 Javascript
JS简单实现点击跳转登陆邮箱功能的方法
2017/10/31 Javascript
vue滚动固定顶部及修改样式的实例代码
2019/05/30 Javascript
layui自定义工具栏的方法
2019/09/19 Javascript
JS document form表单元素操作完整示例
2020/01/13 Javascript
JavaScript实现轮播图片完整代码
2020/03/07 Javascript
vue实现前端分页完整代码
2020/06/17 Javascript
javascript中layim之查找好友查找群组
2021/02/06 Javascript
[06:42]DOTA2每周TOP10 精彩击杀集锦vol.1
2014/06/25 DOTA
用python实现面向对像的ASP程序实例
2014/11/10 Python
python定时执行指定函数的方法
2015/05/27 Python
python开发中range()函数用法实例分析
2015/11/12 Python
python实现决策树分类算法
2017/12/21 Python
python使用matplotlib模块绘制多条折线图、散点图
2020/04/26 Python
python3实现猜数字游戏
2020/12/07 Python
python打造爬虫代理池过程解析
2019/08/15 Python
Golang GBK转UTF-8的例子
2019/08/26 Python
django框架ModelForm组件用法详解
2019/12/11 Python
python3 requests库实现多图片爬取教程
2019/12/18 Python
tensorflow如何继续训练之前保存的模型实例
2020/01/21 Python
python的reverse函数翻转结果为None的问题
2020/05/11 Python
Python爬取豆瓣数据实现过程解析
2020/10/27 Python
北欧最好的童装网上商店:Babyshop
2019/09/15 全球购物
某公司面试题
2012/03/05 面试题
婚庆公司计划书
2014/09/15 职场文书
公司证明怎么写
2014/09/22 职场文书
派出所正风肃纪剖析材料
2014/10/10 职场文书
催款通知书范文
2015/04/17 职场文书
任命书格式范文
2015/09/22 职场文书
《传颂之物 虚伪的假面》BD发售宣传CM公开
2022/04/04 日漫