簡體   English   中英

如何通過 Flask 中的 API 檢查來自 POST 請求的數據類型? 如果傳入的數據不是圖像,則引發錯誤

[英]How to check the type of data coming from POST request through API in Flask? Raising an error if incoming data is not is not an Image

我有一部分代碼是這樣的:

@app.route('/', methods=['POST'])
def predict():
  
   if flask.request.method == 'POST':
           #global mymodel
           first  =datetime.now()
           f = request.files["img"].read()
           f = Image.open(io.BytesIO(f))

此代碼預測圖像是否為垃圾郵件。 我想用消息RaiseCustomError請上傳圖片但為此我需要檢測傳入ByteString的數據類型。 我考慮過在try塊中使用f = Image.open(io.BytesIO(f)) ,所以當發生錯誤時,它可以執行

exception as e:
    return e

但在我自己看來,這樣做很愚蠢。

如何從 POST 請求中檢測數據類型,以便如果它不屬於任何 Image 類型,我可以通過消息引發自定義錯誤。

`

檢查文件擴展名是否在允許列表中。 您可以使用您想要允許的圖像類型自定義列表。 例如,

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ["png", "jpg"]

在閱讀圖像之前,您可以像這樣檢查擴展名

given_file = request.files["img"]
if given_file and allowed_file(given_file.filename):
    # Write your code here
else:
    abort(400, 'File is not a valid image type')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM