【问题标题】:Flask custom error handling for upload function上传功能的烧瓶自定义错误处理
【发布时间】:2018-11-26 09:33:59
【问题描述】:

我已经开发了一个上传表单来上传特定的 .xlsx 文件。要求是处理上传非 xlsx 的任何异常(例如 zip、exe 文件)。我正在使用 pyexcel 库来阅读上传。我尝试创建以下代码来处理此异常:

enter image description here enter image description here

错误处理代码如下:

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

上传代码如下:

@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)

我无法弄清楚如何正确捕获错误并进行处理,我们将不胜感激。

【问题讨论】:

    标签: flask error-handling pyexcel


    【解决方案1】:

    您有两种选择来处理此异常。

    1)你直接从pyexcel包中导入异常并将其作为错误:

    例如

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

    2) 或者,您可以将要加载电子表格的代码包装在 try-except 块中并引发自定义错误。

    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
    

    【讨论】:

    • 感谢您的反馈。我会试试这个并恢复。干杯!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 2018-08-11
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    • 2021-05-20
    • 2021-01-02
    相关资源
    最近更新 更多