how to handle-attributeerror:'nonetype'对象没有属性'patient\u id'

jhdbpxl9  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(403)

在这里寻找一些指导。我想知道如何处理这个问题标题中的异常。在代码下面发布的完整错误。
一些上下文:在测试期间-我的python脚本中下面的代码块在db中有匹配的患者时工作,但是在db表中没有匹配的“patient\u id”时抛出异常。我希望能以某种方式处理这个异常。也许我只需要重写我的if not语句。我需要能够解释/处理来自用户的通配符条目,例如,我的db具有患者ID“1到10”。当用户输入“1到10”时,代码工作正常。例如,如果用户输入11,则得到异常。我需要处理一下。
感谢建设性的反馈。

def delete_patient():
    if not request.form['pid']:
        flash("Field cannot be empty when deleting a Patient.", "orange")

# function takes mandated user input via request form

    else:
        trashXX = request.form['pid']
        trash02 = silver.query.filter_by(patient_id=request.form['pid']).all()
        for i in trash02:
            divo.session.delete(i)
            divo.session.commit()
        trash03 = gold.query.filter_by(patient_id=trashXX).first()
        divo.session.delete(trash03)
        divo.session.commit()
        flash("Patient Deleted Successfully", "green")
    return redirect(url_for('show_patients'))

# function uses mandated user input as a a filter to locate patient (and records) in DB

# function locates a valid patient in DB, and proceeds to delete patient records first, and patient second.

完全例外:

AttributeError: 'NoneType' object has no attribute 'patient_id'
Traceback (most recent call last)

    File "C:\Python39\Lib\site-packages\flask\app.py", line 2464, in __call__

    return self.wsgi_app(environ, start_response)

    File "C:\Python39\Lib\site-packages\flask\app.py", line 2450, in wsgi_app

    response = self.handle_exception(e)

    File "C:\Python39\Lib\site-packages\flask\app.py", line 1867, in handle_exception

    reraise(exc_type, exc_value, tb)

    File "C:\Python39\Lib\site-packages\flask\_compat.py", line 39, in reraise

    raise value

    File "C:\Python39\Lib\site-packages\flask\app.py", line 2447, in wsgi_app

    response = self.full_dispatch_request()

    File "C:\Python39\Lib\site-packages\flask\app.py", line 1952, in full_dispatch_request

    rv = self.handle_user_exception(e)

    File "C:\Python39\Lib\site-packages\flask\app.py", line 1821, in handle_user_exception

    reraise(exc_type, exc_value, tb)

    File "C:\Python39\Lib\site-packages\flask\_compat.py", line 39, in reraise

    raise value

    File "C:\Python39\Lib\site-packages\flask\app.py", line 1950, in full_dispatch_request

    rv = self.dispatch_request()

    File "C:\Python39\Lib\site-packages\flask\app.py", line 1936, in dispatch_request

    return self.view_functions[rule.endpoint](**req.view_args)

    File "<path>\tahnApp_01.py", line 226, in delete_patient

    trashXX = trash02.patient_id

    AttributeError: 'NoneType' object has no attribute 'patient_id'
t9aqgxwy

t9aqgxwy1#

你可以用 hasattr() 或接住 AttributeError 但是python社区推荐一种策略“请求宽恕比请求许可更容易”,因此您应该在 try - except 块,像这样:

try:
    if obj['patient_id']: # Look for attribute
        pass
except AttributeError:
    # Attribute not found, handle error
    pass

如果你的 obj 可以是 None ,从错误(attributeerror:'nonetype'对象没有属性'patient\u id')可以看出,处理这种情况是一种很好的做法:

if obj:
    try:
        if obj['patient_id']: # Look for attribute
            pass # Do something
    except AttributeError:
        # Attribute not found
        pass # Handle error
else:
    print('obj is None!')

您可以在这里找到关于异常处理的更多信息:python文档
另一种选择是,如果对象具有使用 hasattr() :

if obj:
    if hasattr(obj, 'property'):
        pass # Do something
    else:
        pass # Handle the missing attribute
else:
    pass: # Handle the missing object

如果希望属性的值具有默认值(如果不存在),则可以使用 getattr() :

if obj:
    a = getattr(obj, 'property', 'default value')
else:
    pass # Handle the missing object

相关问题