[英]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
I have a portion of code like this:我有一部分代码是这样的:
@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))
This code predicts whether an image is Spam or not.此代码预测图像是否为垃圾邮件。 I want to
RaiseCustomError
with a messsage Please upload an image But for this I need to detect the data type of the incoming ByteString
.我想用消息
RaiseCustomError
请上传图片但为此我需要检测传入ByteString
的数据类型。 I have thought about using the f = Image.open(io.BytesIO(f))
inside a try
block so when an error occurs, it can perform我考虑过在
try
块中使用f = Image.open(io.BytesIO(f))
,所以当发生错误时,它可以执行
exception as e:
return e
but that is stupid to do in my own opinion.但在我自己看来,这样做很愚蠢。
How can I detect the type of data from POST request so that if it not something belonging to any of Image type, I can raise a custom error with a message.如何从 POST 请求中检测数据类型,以便如果它不属于任何 Image 类型,我可以通过消息引发自定义错误。
` `
Check the file extension whether they are in the allowed list.检查文件扩展名是否在允许列表中。 You can customize the list with the image type that you wanna allow.
您可以使用您想要允许的图像类型自定义列表。 For example,
例如,
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ["png", "jpg"]
Before reading the image you can check the extension like this way在阅读图像之前,您可以像这样检查扩展名
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.