工作中用到这一点,当时赶时间,直接写死的文件路径,上传后得到fileid,其实这样就不太好了,如果今后有了业务变化,就要不断的该,修改后的通用代码如下
调用格式如下,cluster代表集群名称,index代表主页面,attachment代表附属目录
put_file_msg.py --cluster 集群名称 --title "" --index index1.html --attachments files1
import argparse
import os
import requests
import string
def upload_file(upload_url_path, base_url , file_path):
if os.path.exists(file_path):
print "file exists"
else:
print "not exist"
return
file_data = [('file1', (file_path, open(file_path, 'r')))]
r = requests.post(upload_url_path, files=file_data)
#print r["value"][0]["file_id"]
content = r.__dict__["_content"]
file_info = (eval(content))["value"][0]
ret = {}
name = file_info["file_name"]
file_name = name.replace(base_url,'')
ret["file_name"] = file_name
ret["file_id"] = file_info["file_id"]
#print str(ret)
return ret
#return file_att_list[0]
if __name__ == '__main__':ii
parser = argparse.ArgumentParser()
parser.add_argument('--cluster', type=str, default = None)
parser.add_argument('--title', type=str, default=32)
parser.add_argument('--index', type=str, default = None)
parser.add_argument('--attachments', type=str, default = None)
args = parser.parse_args()
cluster = args.cluster
title = args.title
index = args.index
attachments = args.attachments
upload_url_path = ‘文件服务器地址’
file_path = ‘路径’
index_path = file_path + index
attachments_path = file_path + attachments
ret = []
#upload the html file
index_info = upload_file(upload_url_path, file_path, index_path)
ret.append(index_info)
#upload the directory
for (root, dirs, files) in os.walk(attachments_path):
for filename in files:
subfile_path = os.path.join(root, filename)
attch_info = upload_file(upload_url_path, file_path, subfile_path)
ret.append(attch_info)
for dirc in dirs:
subfoler_path = os
os.path.join(root, dirc)
for i in ret:
print str(i)