flask和flask-restful接收file请求处理,以及压缩文件处理

import werkzeug
from flask import Flask
import tarfile
from flask_restful import Resource, Api, reqparse
from werkzeug.datastructures import FileStorage
from werkzeug.utils import secure_filename

app = Flask(__name__)
api = Api(app)


parser = reqparse.RequestParser()
parser.add_argument('picture', type=werkzeug.datastructures.FileStorage, location='files')


class HelloWorld(Resource):
    def post(self):
        args = parser.parse_args()
        content = args.get('picture')
        filename = secure_filename(content.filename)
        content.save(os.path.join('/home/zlp/', filename))
        
        def extract(tar_path, target_path):
            try:
                tar = tarfile.open(tar_path, "r:gz")
                file_names = tar.getnames()
                for file_name in file_names:
                    tar.extract(file_name, target_path)
                tar.close()
            except Exception as e:
                raise e
        extract('/home/zlp/{}'.format(filename), '/home/zlp/result')
        return {'hello': 'world'}


api.add_resource(HelloWorld, '/')

if __name__ == '__main__':
    app.run(debug=True)

上面是一个小demo,直接可以拿去测试,我测试的是一个tar.gz包

处理压缩文件:

一、zip

import os, zipfile
#打包目录为zip文件(未压缩)
def make_zip(source_dir, output_filename):
  zipf = zipfile.ZipFile(output_filename, 'w')
  pre_len = len(os.path.dirname(source_dir))
  for parent, dirnames, filenames in os.walk(source_dir):
    for filename in filenames:
      pathfile = os.path.join(parent, filename)
      arcname = pathfile[pre_len:].strip(os.path.sep)   #相对路径
      zipf.write(pathfile, arcname)
  zipf.close()

二、tar/tar.gz

import os, tarfile
#一次性打包整个根目录。空子目录会被打包。
#如果只打包不压缩,将"w:gz"参数改为"w:"或"w"即可。
def make_targz(output_filename, source_dir):
  with tarfile.open(output_filename, "w:gz") as tar:
    tar.add(source_dir, arcname=os.path.basename(source_dir))



#逐个添加文件打包,未打包空子目录。可过滤文件。
#如果只打包不压缩,将"w:gz"参数改为"w:"或"w"即可。
def make_targz_one_by_one(output_filename, source_dir):
  tar = tarfile.open(output_filename,"w:gz")
  for root,dir,files in os.walk(source_dir):
    for file in files:
      pathfile = os.path.join(root, file)
      tar.add(pathfile)
  tar.close()

三、多个不同目录下的文件打包成一个tar

def make_targz(output_filename, source_dir):
    with tarfile.open(output_filename, "w:gz") as tar:
        for dir in source_dir:
            tar.add(dir, arcname=os.path.basename(dir))


if __name__ == '__main__':
    make_targz('/home/zlp/zlp.tar.gz', ['/home/zlp/result','/home/zlp/Desktop/teston2'])

 

你可能感兴趣的:(python,request,tar)