前情回顾
上一篇文章已经编写了跨文件目录引入mysql的封装类,那么本章节我们来继续编写封装Http请求的基本类方法。
实战任务
本次因为服务架构重构,表优化、重构,带来的任务就是需要从原来的mysql数据库中,读取原表数据(部分存在多张关联查询)然后通过调用API的服务方式灌入新的数据库表中(包含mysql、mongodb)。
执行流程如下
那么根据流程所需要的功能,需要以下的实例进行支撑: 1.并发实例 2.查询数据实例 3.执行post请求实例
目标:编写Http执行POST请求的基本类方法
编写Http执行POST请求基本类方法
# coding:utf-8
import urllib2,json
class PostHelper(object): # 继承object类所有方法
def post(self, url , headers , body):
self.data = json.dumps(body)
try:
request = urllib2.Request(url, self.data, headers) # urllib2用一个Request对象来映射你提出的HTTP请求
print request
response = urllib2.urlopen(request) # 通过调用urlopen并传入Request对象,将返回一个相关请求response对象
print response
message = response.read() # 这个应答对象如同一个文件对象,所以你可以在Response中调用.read()
print "message=",message
return self.check_ResuleCode(message)
except Exception as e:
print str(e)
def check_ResuleCode(self,message):
hjson = json.loads(message)
# print hjson['resultCode']
if hjson['resultCode'] == 0:
# print "implements sucessful!"
return True
else:
# print "implements fail!"
return False
if __name__ == "__main__":
# 定义请求参数
url='你需要发送的API请求的url'
body = {‘######注释请求体######’}
headers={
'Content-Type':'application/json',
....
# 补充你所需的请求头信息
} #头部
# 初始化请求类
httpPost = PostHelper()
# 执行post请求
result = httpPost.post(url,headers,body)
# 判断是否执行成功
if result:
print "insert sucessful"
else:
print "insert fail"
执行结果如下:
message= {"resultCode":0,"message":null,"data":{"id":"1067....,"accessory":null}
insert sucessful
现在有了post请求的工具类方法了,那么下一步就来看看如何使用test02.py的测试脚本来调用一下看看。
编写test02.py测试方法
# -*- coding: utf-8 -*-
from tools.PostTools import PostHelper
if __name__ == "__main__":
# 定义请求参数
url='服务API接口url地址'
body = {‘######注释请求体######’}
headers={
'Content-Type':'application/json',
..... 头部参数
} #头部
# 初始化请求类
httpPost = PostHelper()
# 执行post请求
result = httpPost.post(url,headers,body)
# 判断是否执行成功
if result:
print "insert sucessful"
else:
print "insert fail"
到了这里应该可以比较简化地使用Http的请求了,那么下一步就可以结合mysql查询出来的数据,使用http请求进行数据灌入了。