0

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. I have thought about using the f = Image.open(io.BytesIO(f)) inside a try block so when an error occurs, it can perform

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.

`

Deshwal
  • 3,436
  • 4
  • 35
  • 94
  • "but that is stupid to do in my own opinion." - Why is that? Using try/except in this case is [very pythonic](https://stackoverflow.com/a/16138864/4032503). The accepted answer of using file extensions is extraordinarily naive, especially since you are trying to identify spam. Spoofing a file extension is trivial, especially in the spamming world where they are always trying to get around spam detection schemes. – noslenkwah Jun 29 '20 at 21:09
  • NO..you got me wrong. This is supposed to be a Machine Learning Spam. I want to identify my kind of spams and throw an error when there is something else uploaded than image extension. – Deshwal Jun 30 '20 at 07:11

1 Answers1

0

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')
Md Shafiul Islam
  • 1,579
  • 1
  • 13
  • 19