我非常新手Python,我有一个任务需要逐行解析一个非常庞大的.csv文件,然后基于逗号分隔的值,调用REST API。有人能帮我提供一份示例代码吗?
根据CSV文件中的第一列值,我必须调用不同的REST API或创建不同的REST URL及其对应的参数。最好的方法是将它们存储在哪里?是使用XML、哈希映射还是其他什么方式?这样,当我从CSV读取每一行时,我可以从我的配置中获取URL和所需参数,然后组成REST API的URL并调用。
第二个问题:我们是否需要创建任何线程以使其执行更快?
下面是我的代码。
import sys, argparse, csv, collections, time, datetime
EventAPIDict = {"evnet_1": "http://rest_apiurl/?",
"evnet_2": "http://rest_apiurl/?"}
EventParamsDict = {"evnet_1": ("s", "ts"),
"evnet_2": ("s")}
EventIndexDict = {"evnet_1": ("1", "4"),
"evnet_2": ("1")}
def processRow(row):
print "-----------------------------"
#print localRow
event = row[0]
if event in EventAPIDict:
print event
strRESTAPI = EventAPIDict[event]
i = 0
for param in EventParamsDict[event]:
#print param
indexes = EventIndexDict[event]
value = row[int(indexes[i])]
if param == "ts":
timestamp = value #"2013-05-28 14:28:58"
value = datetime.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S').strftime("%s")
strRESTAPI = ("%s%s=%s&")%(strRESTAPI, param, value)
i = i + 1
strRESTAPI = strRESTAPI[:-1]
print strRESTAPI
#TODO: Invoke the Rest API
#TODO: Get the csv file to be parsed.
fileName = "LogDetails.log"
# open csv file
with open(fileName, 'rb') as csvfile:
csvfile.seek(0)
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
processRow(row)
csv
文件有多大? - agconti