Flask 上传文件小例子

作者: ropon 分类: Flask 发布时间: 2019-03-28 11:45
from flask import Flask, views, request, jsonify

app = Flask(__name__)

pkey = 'xxxxxx'
host = '127.0.0.1'
port = 9080
data = {'code': 200, 'msg': None}
# use:
# curl -F "rfile=@d:\12.txt" -F "ukey=xxxxxx" http://127.0.0.1:9080/upfile


class UpFile(views.MethodView):
    methods = ['GET', 'POST']
    decaorators = ['app.route']

    def get(self):
        data['code'] = 202
        data['msg'] = 'forbidden'
        return jsonify(data)

    def post(self):
        ukey = request.form.to_dict().get('ukey')
        rfile = request.files.get('rfile')
        if ukey == pkey and rfile is not None:
            rfilename = rfile.filename
            rfile.save(rfile.filename)
            data['msg'] = '%s upload success' % rfilename
        else:
            data['code'] = 201
            data['msg'] = 'error'
        return jsonify(data)


app.add_url_rule("/upfile", view_func=UpFile.as_view("upfile"))

if __name__ == '__main__':
    app.run(host=host, port=port)

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!