最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

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

来源:动视网 责编:小采 时间:2020-11-27 14:31:10
文档

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

python服务器端收发请求的实现代码:最近学习了python的一些服务器端编程,记录在此。 发送get/post请求 # coding:utf-8 import httplib,urllib #加载模块 #urllib可以打开网站去拿 #res = urllib.urlopen('http://baidu.com'); #print res.headers
推荐度:
导读python服务器端收发请求的实现代码:最近学习了python的一些服务器端编程,记录在此。 发送get/post请求 # coding:utf-8 import httplib,urllib #加载模块 #urllib可以打开网站去拿 #res = urllib.urlopen('http://baidu.com'); #print res.headers


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


	
	


this is get!

"""+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("""

this is put!

"""+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服务器端收发请求的实现代码:最近学习了python的一些服务器端编程,记录在此。 发送get/post请求 # coding:utf-8 import httplib,urllib #加载模块 #urllib可以打开网站去拿 #res = urllib.urlopen('http://baidu.com'); #print res.headers
推荐度:
标签: 发送 请求 python的
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top