【问题标题】:How to give image as an user input in api request using flask in python如何在 python 中使用 flask 在 api 请求中将图像作为用户输入
【发布时间】:2022-11-18 01:47:41
【问题描述】:

我正在创建一个 API,我想在其中提供图像作为用户输入。

我知道request.args.get 以字典格式接受用户输入。我想知道用户是否可以通过任何方式在下面的 api 脚本中将图像作为输入提供给 api。

我的图片路径是E:\env\abc.png

一个.py

import pandas as pd
from datetime import datetime
from pandas import json_normalize
from flask import request, Flask, Response
from flask_cors import CORS
app = Flask(__name__)
CORS(app)

@app.route("/api_endpoint", methods=["GET"])
def function_for_api():
    
    user_input_image = request.args.get('user_input_image')
    print("USER IMAGE",user_input_image)

    status = 200
    resJson = "python_file_name output will be here in json format"
    return Response(response=resJson, status=status, mimetype="application/json")

if __name__ == "__main__":
    app.run()

【问题讨论】:

    标签: python api rest flask


    【解决方案1】:

    首先,此方法应该是 POST 而不是 GET。您正在将信息放在服务器上。其次,您想从 files 参数而不是查询参数之一读取文件。

    @app.route("/api_endpoint", methods=["POST"])
    def function_for_api():
        img = request.files['file']
        print(img.filename)
        return Response(status=200)
    

    这是您可以调用此函数上传图像的示例。

    import requests
    pic_file = "picture_filename"
    # post a request with file and receive response
    with open(pic_file, 'rb') as f:
        resp = requests.post(f"{your_server_address}/api_endpoint", files={'file': f})
    

    【讨论】:

    • 我们是否需要在 api 请求中提供图像的完整路径。例如:pic_file =E:envbc.png
    • 你不需要。您可以从执行 python 文件的任何地方给它一个相对路径,但完整路径可能是最简单和最好的。
    猜你喜欢
    • 2023-03-18
    • 2022-11-11
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-20
    • 1970-01-01
    • 2014-10-03
    相关资源
    最近更新 更多