flaskerror-handlingpyexcel

Flask custom error handling for upload function


I have developed an upload form to take specific .xlsx file as upload. The requirement is to handle any exceptions for upload of non xlsx (for e.g. zip, exe file). I am using pyexcel library for reading the upload. I tried creating following code to handle this exception:

enter image description here enter image description here

The error handling code is as follows:

class FILE_TYPE_NOT_SUPPORTED_FMT(Exception):
pass

@app.errorhandler(FILE_TYPE_NOT_SUPPORTED_FMT)
def custom_handler(errrors):
app.logger.error('Unhandled Exception: %s', (errrors))
return render_template('400.html'), 400

and the upload code is as follows:

@users.route("/oisdate_upload", methods=['GET', 'POST'])
@login_required
def doimport_ois_date():
msg=None
if request.method == 'POST':

def OIS_date_init_func(row):
#c.id = row['id']
c = Ois_date(row['date'],row['on'],row['m1'],row['m2'],row['m3'],row['m6'],row['m9'],row['y1'],row['y2'],row['y3'],row['y4'],row['y5'],row['y7'],row['y10'])
return c

request.save_book_to_database(
field_name='file', session=db.session,
tables=[Ois_date],
initializers=[OIS_date_init_func])
msg = "Successfully uploaded"
#return redirect(url_for('users.doimport_ois_date'), code=302)
if((Ois_date.query.order_by(Ois_date.date.desc()).first()) is not None):
date_query = Ois_date.query.order_by(Ois_date.date.desc()).first()
start_date = date_query.date
date_query1 = Ois_date.query.order_by(Ois_date.date.asc()).first()
end_date = date_query1.date

return render_template('OISdate_upload.html',msg=msg, start_date=start_date,end_date=end_date)

I am unable to figure out how to correctly capture the error and handle it, any feedback would be appreciated.


Solution

  • You have two options to handle this exception.

    1) you import the exception directly from the pyexcel package and use it as the error:

    e.g.

    from pyexcel.exceptions import FileTypeNotSupported
    ...
    @app.errorhandler(FileTypeNotSupported)
    ...
    

    2) Or, you can wrap the code where you want to load the spreadsheet in a try-except block and throw a custom error.

    from pyexcel.exceptions import FileTypeNotSupported
    
    class CustomError(Exception)
        pass
    
    @app.errorhandler(CustomError)
        # do something
        pass
    
    @app.route('/upload_excel')
    def upload_excel():
        try:
            function_where_you_load_excel()
        except FileTypeNotSupported:
            raise CustomError