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的Django REST框架中的序列化及请求和返回
Apr 11 Python
python实现从文件中读取数据并绘制成 x y 轴图形的方法
Oct 14 Python
使用python对文件中的单词进行提取的方法示例
Dec 21 Python
对python xlrd读取datetime类型数据的方法详解
Dec 26 Python
Python实现的逻辑回归算法示例【附测试csv文件下载】
Dec 28 Python
python如何获取当前文件夹下所有文件名详解
Jan 25 Python
Python pandas自定义函数的使用方法示例
Nov 20 Python
在Django下创建项目以及设置settings.py教程
Dec 03 Python
Django自定义全局403、404、500错误页面的示例代码
Mar 08 Python
Python爬虫实现自动登录、签到功能的代码
Aug 20 Python
python 实现两个变量值进行交换的n种操作
Jun 02 Python
Python socket如何解析HTTP请求内容
Feb 12 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 url地址栏传中文乱码解决方法集合
2010/06/25 PHP
使用php get_headers 判断URL是否有效的解决办法
2013/04/27 PHP
PHP判断表达式中括号是否匹配的简单实例
2016/10/22 PHP
thinkPHP5使用Rabc实现权限管理
2019/08/28 PHP
prototype 学习笔记整理
2009/07/17 Javascript
用jquery实现学校的校历(asp.net+jquery ui 1.72)
2010/01/01 Javascript
suggestion开发小结以及对键盘事件的总结(针对中文输入法状态)
2011/12/20 Javascript
javascript获取选中的文本的方法代码
2013/10/30 Javascript
javascript自定义startWith()和endWith()的两种方法
2013/11/11 Javascript
XML文件转化成NSData对象的方法
2015/08/12 Javascript
手机端 HTML5使用photoswipe.js仿微信朋友圈图片放大效果
2016/08/25 Javascript
深入理解JS继承和原型链的问题
2016/12/17 Javascript
js实现鼠标拖动功能
2017/03/20 Javascript
Vue实现日历小插件
2019/06/26 Javascript
Node使用Selenium进行前端自动化操作的代码实现
2019/10/10 Javascript
解决VUE项目localhost端口服务器拒绝连接,只能用127.0.0.1的问题
2020/08/14 Javascript
JavaScript读取本地文件常用方法流程解析
2020/10/12 Javascript
深入讨论Python函数的参数的默认值所引发的问题的原因
2015/03/30 Python
python实现多线程的方式及多条命令并发执行
2016/06/07 Python
Python机器学习算法之k均值聚类(k-means)
2018/02/23 Python
TensorFlow实现Softmax回归模型
2018/03/09 Python
python socket网络编程之粘包问题详解
2018/04/28 Python
Python使用mongodb保存爬取豆瓣电影的数据过程解析
2019/08/14 Python
如何通过命令行进入python
2020/07/06 Python
python利用 keyboard 库记录键盘事件
2020/10/16 Python
纯CSS3实现自定义Tooltip边框涂鸦风格的教程
2014/11/05 HTML / CSS
C++面试题:关于链表和指针
2013/06/05 面试题
建筑毕业生自我鉴定
2013/10/18 职场文书
学习十八大坚定理想信念心得体会
2014/03/11 职场文书
农村党员一句话承诺
2014/05/30 职场文书
工地标语大全
2014/06/18 职场文书
批评与自我批评总结
2014/10/17 职场文书
2014年单位法制宣传日活动总结
2014/11/01 职场文书
居住证明范文
2015/06/17 职场文书
新教师教学工作总结
2015/08/14 职场文书
SQL Server2019数据库备份与还原脚本,数据库可批量备份
2021/11/20 SQL Server