python - 如何使用 cURL 在 Flask RESTful 中上传文件?

标签 python python-3.x curl flask-restful

我已经编写了下一个资源:

from config import AWS_S3_BUCKET
from flask_api import status
from flask_restful import Resource, reqparse
from werkzeug.datastructures import FileStorage
from werkzeug.utils import secure_filename
import helpers


class FileUpload(Resource):

    def post(self):
        parse = reqparse.RequestParser()
        parse.add_argument('user_file', type=FileStorage, location='user_file')
        parse.add_argument('user_id', type=int, location='user_id')
        args = parse.parse_args()
        file = args['user_file']
        if file:
            file.filename = secure_filename(file.filename)
            url = helpers.upload_file_to_s3(file, AWS_S3_BUCKET)
            return {'url': url}, status.HTTP_201_CREATED

        return 'Invalid file', status.HTTP_400_BAD_REQUEST

在我尝试通过此命令在 cURL 中上传文件后:

curl -F 'user_file=@recovery.fstab' -F 'user_id=5' http://127.0.0.1:5000/files/new

在调试器中调用端点,但所有字段:user_fileuser_id 均为 NoneType
我做错了什么?
P.S. recovery.fstab 文件位于 home 目录中。

最佳答案

请参阅flask-RESTful docs .

位置参数是 req 解析器从中获取值的位置。

def post(self):
    parse = reqparse.RequestParser()
    parse.add_argument('user_file', type=FileStorage, location='files')
    parse.add_argument('user_id', type=int, location='args')
    ...

关于python - 如何使用 cURL 在 Flask RESTful 中上传文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49723122/

相关文章:

Python 3 使用ElementTree解析xml文件

PHP cURL 只需要发送而不等待响应

shell - 使用curl下载文件时如何保留远程文件名

python - 必须首先创建 wx.app 对象

python - 如何将 'pivot' 数据帧的值放入列中

python - 当两个外键指向同一个表时如何使用工厂男孩

wordpress - curl 显示 gzip,但 chrome 显示没有 gzip header

python - 无法在python中使用posix风格的时区解析解析时间字符串

python-3.x - 如何将点云文件中的数据写入文本文件

python - 使用 pandas 包用 python 清理 excel 数据