遍历文件目录并上传服务器

工作中用到这一点,当时赶时间,直接写死的文件路径,上传后得到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)
    
    
    










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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值