data_download.py 2.1 KB
# coding=utf-8
#author:        4N
#createtime:    2020/11/27
#email:         nheweijun@sina.com


from flask import abort,send_from_directory
from app.modules.auth.models import OAuth2Token,User,db
from app.modules.data.models import Task
import os
from app.util.component.ApiTemplate import ApiTemplate
import configure

class Api(ApiTemplate):

    api_name = "下载"

    def __init__(self,dirname,file):
        super().__init__()
        self.dirname = dirname
        self.file = file


    def process(self):

        parent = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
        dirpath = os.path.join(parent, "file_tmp", self.dirname)

        if configure.PermissionActive:
            token = self.para.get("token")
            if not token:
                abort(401)
            task_guid = self.para.get("task_guid")
            task = Task.query.filter_by(guid=task_guid).one_or_none()
            if not task:
                raise Exception("任务不存在!")

            user = User.query.join(OAuth2Token).filter(OAuth2Token.access_token == token).one_or_none()
            if not user:
                abort(403)
            if user.username != task.creator:
                if user.username != "admin":
                    abort(403)
            if not os.path.exists(os.path.join(dirpath,self.file)):
                raise Exception("数据不不存在了!")

        return send_from_directory(dirpath, filename=self.file, as_attachment=True)


    api_doc={
    "tags":["IO接口"],
    "description":"下载数据",
    "parameters":[
        {"name": "token",
         "in": "formData",
         "type": "string","required":"true"
         },
        {"name": "task_guid",
         "in": "formData",
         "type": "string","required":"true"
         }
    ],
    "responses":{
        200:{
            "schema":{
                "properties":{
                    "content":{
                        "type": "string",
                        "description": "The name of the user"
                    }
                }
            }
            }
        }

}