【问题标题】:Python3 flask receive file and send it to another apiPython3烧瓶接收文件并将其发送到另一个api
【发布时间】:2020-04-19 01:27:56
【问题描述】:

我正在尝试通过 post 请求在 python 烧瓶端点中接收文件,然后将其发送到另一个端点。我在我的 API 上收到一个文件,但我不知道如何为下一个请求包装它。

代码如下所示

@app.route('/file', methods=['POST'])
def get_task_file():
    response_obj = {} 
    if 'file' not in request.files:
        abort(400) 

    print(request.files["file"].filename)

    # TEXT EXTRACT
    url1 = 'http://localhost:5001/text/api' 
    headers = {'Content-type': 'multipart/form-data'} 

    print(type(request.files['file']))  

    r1 = requests.request("POST", url1, files={'file':request.files['file']}, headers=headers)

    print(r1.text)

现在文件类型是<class 'werkzeug.datastructures.FileStorage'>,我收到 400 个错误。我只是想补充一下,第二个API上的逻辑是相似的,我应该改变它吗?

【问题讨论】:

  • <class 'werkzeug.datastructures.FileStorage'> 似乎是一个像对象这样的文件的薄包装,而不是文件本身。 tedboy.github.io/flask/generated/generated/…试试request.files['file'].read()
  • 不幸的是,它没有帮助。到目前为止唯一有效的方法是将文件保存在本地,然后使用 'rb' 标志打开它。但必须有更好的方法。
  • 找到了一个看起来很有希望的答案stackoverflow.com/questions/24678673/…
  • 遇到了同样的问题,你解决了吗?

标签: python api file flask request


【解决方案1】:

我得到代码:400 作为返回,或者它显示我上传的文件是空的,我发现烧瓶中的requests 有点棘手。 改变这个

r1 = requests.request("POST", url1, files={'file':request.files['file']}, headers=headers)

进入:

file = request.files['file']
r1 = requests.post(url1, files={'file':(file.filename, file.stream, file.content_type, file.headers)})

【讨论】:

    猜你喜欢
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 2018-09-25
    • 2019-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多