gpt4 book ai didi

python - 为什么我的 `else` block 的 `try` 部分的代码没有运行?

转载 作者:太空宇宙 更新时间:2023-11-03 14:24:53 27 4
gpt4 key购买 nike

我将 Python 2.7.3 与 Flask 0.10.1 和 SQL-Alchemy 0.9.1 一起使用。

在我的 View 代码中,我正在为数据库输入构建一个对象,我的代码取决于两个 try/except/else 的正确执行 block 。对于第一个 block ,无论发生异常还是不发生异常,它都按预期工作。当出现异常时,我会得到一组错误。如果没有异常,数据会添加到数据库中并且样本计数器会增加。这是该片段:

        try:
new_sample = Sample()
new_sample.build(sample)
except SampleBuildingError as e:
result_response['errors'].append('{0}: {1}'.format(sample['sample_name'], e.value) )
else:
db.session.add(new_sample)
num_added += 1

在 View 函数的更下方,我有一个 try/except/else/finally block 。数据被提交到数据库,所以 try 部分显然有效,finally block 也是如此。但是,else block 似乎没有被执行:

try:
db.session.commit()
except Exception as e:
result_response['error'] = "Failed on the database input: {0}".format( str(e) )
else:
result_response['success'] = "The samples were input to the database successfully. {0} samples entered into the database, with {1} errors".format( num_added, len(errors) )
finally:
return jsonify(result_response)

当出现异常时,我按预期返回带有 error 键和数据库错误的 json。但是,当数据库提交成功时,我得到一个 json 对象,其中包含每个预期的键 success 键。

else block 似乎被跳过了,但我不明白为什么。我试过将单词 bogus 放在 else block 的第二行以尝试强制出错,但 Python 没有提示!

完整 View 函数如下:

@app.route("/kapasubmit", methods=['POST'])
def kapasubmit():
num_added = 0
result_response = {'errors': []}
samples = request.json['data']
for sample in samples:
sample_check = Sample.query.filter_by( sample_name = sample['sample_name'] ).first()
if sample_check is None:
try:
new_sample = Sample()
new_sample.build(sample)
except SampleBuildingError as e:
result_response['errors'].append('{0}: {1}'.format(sample['sample_name'], e.value) )
else:
db.session.add(new_sample)
num_added += 1
else:
result_response['errors'].append('{0}: This is a duplicate sample'.format(sample['sample_name']) )

if num_added > 0:
try:
db.session.commit()
except Exception as e:
result_response['error'] = "Failed on the database input: {0}".format( str(e) )
else:
result_response['success'] = "The samples were input to the database successfully. {0} samples entered into the database, with {1} errors".format( num_added, len(errors) )
bogus
finally:
return jsonify(result_response)
else:
result_response['error'] = "No valid samples submitted for input"
return jsonify(result_response)

最佳答案

如果 else block 引发异常,它会被忽略,因为解释器必须从函数执行 return。演示:

>>> def divide(x, y):
... try:
... result = x / y
... except ZeroDivisionError:
... print "division by zero!"
... else:
... print "result is", result
... print 1/0
... finally:
... return 1
...
>>> divide(2,1)
result is 2
1

1/0 不会导致任何回溯。

关于python - 为什么我的 `else` block 的 `try` 部分的代码没有运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22080680/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com