python循环读取接口

工作上遇到的一些统计工作

Posted by 九块腹肌的徐先生 on 2021-01-05
Estimated Reading Time 2 Minutes
Words 503 In Total
Viewed Times

工作上总是遇到需要统计的工作,领导觉得数据不都在数据库里么,select * 一下不就都有了么。但是实际上需求总是总是超乎你的能力。并不是select * 就可以搞定,有时候需做一些规则,也就是你的统计依据,依靠这个依据我们批量统计。今天记录一下如何批量统计。

业务逻辑

自己的逻辑当然自己写,这里没有统一标准,一般会准备一个服务,也就是接口。调用接口返回最后的统计结果。当然接口封装依旧可以用python。没有什么不是python搞不了的。这里不赘述了。

如何无脑的调用接口并写入文件

这个小脚本是通过读取Excel里的站号,记录这个站的情况,查询的日期作为一个参数,站号是另一个参数,两个参数在get请求里拼接到url中,最后把结果输出到文本里。这里值得一提的是,需要一些数据处理的类库,比方说pandas用来读取Excel、 requests 用来处理http请求,通过循环方式读取站号,请求接口,写出结果。

看代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import requests
import pandas as pd
import sys

if __name__ == '__main__':
# reload(sys)
# sys.setdefaultencoding('utf8')
df=pd.read_excel('station.xlsx')
df_li=df.values.tolist()
resArray=[]
datestr=input('请输入要查询的索引日期,例如20201001:')
# datatime=raw_input('请输入资料日期,例如2020-08-12:')
#datestr="20200814"
#datatime="2020-08-14"
for i in df_li:
resArray.append(i[0])
# print resArray
# url='http://接口IP/statisticforstation/frontapi/v1/execute?' \
# 'processId=32b25205edb242e48b2c6ab5f6b93885&' \
# 'datestr={my_datestr}'.format(my_datestr=datestr)
url='http://接口IP地址/statisticforstation/frontapi/v1/execute?' \
'processId=7df1b9f8f4234037a0e6ce7d383430fa&' \
'datestr={my_datestr}'.format(my_datestr=datestr)
#print url
v1 ='54511'
#param={"station":v1}
#res=requests.get(url,params=param)
#print param
#print res.text
fo=open("result.txt","w+")
for v in resArray:
# print type(v)
v1=v
param={"station":v1}
# print type(v1)
v2=str(v)
res=requests.get(url,params=param)
print (v1,res.text)
fo.writelines(v2+" "+res.text+"\n")
print ("Successful!")
fo.close()
input()
# print

If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !