使用Python编写自定义脚本

使用Python编写自定义脚本

你需要具备以下工作知识:

  • JSON 
  • Python

 

自定义脚本文件结构

  1. 进口所需的包 
  2. 得到输入参数
  3. 实现的逻辑 
  4. 返回JSON

 

常用包

 

包装

使用

Sys

获取输入参数

json

操纵JSON数据

请求

使API调用

日期

将时间从毫秒转换为所需的日期格式

 

获取输入参数

 

脚本文件参数可以使用sys获取。索引从1开始到传递参数的数量。

当传递的参数为$COMPLETE_V3_JSON_FILE(包含请求JSON的文件的路径)时,可以使用以下代码读取JSON文件:

file_Path = sys.argv[1]
with open(file_Path) as data_file:
data = json.load(data_file)

 

实施逻辑

 

进行API调用的代码片段:

with requests.Session() as s:
url = 'api_url'
r = s.post(url,verify=True, data=post_data,headers=headers)

 

根据需要构造api_url、post_data和header。

将时间从millisec转换为所需的日期格式:

date = datetime.datetime.fromtimestamp(int(millisec)/1e3).strftime('%d %b %Y, %H:%M:%S')

 

构建返回JSON

 

A sample JSON such as {"key":"value"} construction:

json = {}

json["key"] = "value"

print(json)

 

A sample JSON array such as [{"key":"value"}] construction:

json = {}

json["key"] = "value"

result = []

result.append(json)

print(result)

 

 

<<Sample Scripts>>