python解析response_python3.4.3 调用http接口 解析response xml后插入数据库

#!/usr/bin/python3

importtimeimportpymssqlimporturllib.parseimporthttplib2importos.pathimportxml.etree.ElementTreeimportcx_Oracle

v_curr_datetime= time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))print ('Step1:' +v_curr_datetime)##连接sqlServer,获得请求xml,写入txt文件##########################conn_req = pymssql.connect(host="***",user="***",password="***",database="***",charset = "utf8")

conn_req = pymssql.connect(host="***",user="",password="",database="ods",charset = "utf8")

cur_req=conn_req.cursor()

v_file_name_req= 'requestList.txt'f_req= open(v_file_name_req, 'w')

f_req= open(v_file_name_req, 'r+')

f_req.truncate()

v_sql_req= "SELECT Loan_No,request_xml FROM if_haier_loan_contract_list"cur_req.execute(v_sql_req)

rows=cur_req.fetchall()for row_req inrows:#row_req = row_req[0]+'||'+row_req[1]+'\n'

row_req = row_req[0] + '||' + 'kfs;serv10000100056;' + row_req[1] + '\n'

print(row_req)

f_req.write(row_req)

f_req.close()

cur_req.close()

conn_req.close()print ('Step2:' + time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())))##循环得到的xml文件,逐个调用还款计划接口,解析后存到数据库##############

f_read = open('requestList.txt', 'r')for v_row_read inf_read:

v_row_read= v_row_read.split('||')print ('当前调用xml:' + v_row_read[1])

http=httplib2.Http()

url= 'http://***'

#body_str ='kfs;serv10000100056; <?xml version="1.0" encoding="gb2312" standalone="yes"?>serv100001000561257393HCF-CSCP2015070870290400101400515xxx0010ALL'

body_str = v_row_read[1]

headers= {'Content-type': 'application/x-www-form-urlencoded'}print ('*'*30)##请求接口数据#################

response, content = http.request(url, 'POST', headers=headers, body=body_str)##将xml头的gb2312替换成utf-8###

print ('*'*20)

v_response= content.decode("utf-8").replace('encoding=\"gb2312\"','encoding=\"utf-8\"')##将response生成xml文件#######

v_file_name = v_row_read[0] + '.xml'f= open(v_file_name, 'w')

f.truncate()

f.write(v_response)

f.write('\n')

f.close()##读取xml####################

root=xml.etree.ElementTree.parse(v_file_name)##连接数据库##################

connMAPP = cx_Oracle.connect("user","password","tnsname")

cur1=connMAPP.cursor()##将数据写入数据库#############

#book=root.findall('MX')

book=root.iter('MX')for book_list inbook:#print ('='*20)

v_row =[]for note inbook_list:

v_temp=v_row.append(note.text)#v_row = v_row.split(',')

#print (v_row)

v_sql= "insert into temp_py values (%(v0)s,to_date(\'%(v1)s\','YYYY-MM-DD'))"%{'v0':v_row[0],'v1':v_row[1]}#print (v_sql)

cur1.execute(v_sql)##commit后关闭数据库连接

connMAPP.commit()

cur1.close()

connMAPP.close()print ('Step3:' + time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值