我使用Python 2.7.3和Flask 0.10.1和SQL-Alchemy 0.9.1。为什么我的`try`块的`else`部分中的代码没有运行?
在我的视图代码中,我构建了一个数据库输入对象,并且我的代码依赖于两个块的正确执行。它在第一个区块的预期工作,无论是在发生异常时还是在不发生时。当有例外时,我收到errors
的集合。当没有异常时,数据将被添加到数据库中,并且样本计数器递增。下面是摘录:
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
视图功能再往下,我有一个try
/except
/else
/finally
块。数据正在提交给数据库,所以try
部分显然是工作的,finally
块也是如此。然而,似乎没有被执行的else
块:
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)
当有一个例外,我得到的JSON回来了,还error
键和数据库错误,符合市场预期。但是,当数据库提交成功时,我得到一个json对象,其中包含除之外的所有预期密钥success
密钥。
看来else
块正在跳过,但我不明白为什么。我试着在else块的第二行放置bogus
这个词来试图强制一个错误,但是Python不会抱怨!
下面是完整的视图功能:
@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)
我已经做了一个快速测试,'>>>试试: ......通过 ...除了: ......通过 ...别的: ...打印 '其他' ...终于: ...打印'终于' ... 其他 终于 '这似乎工作。必须有别的东西。 – njzk2
@ njzk2对,因为第一个陈述完全按照它应该的方式工作,所以都令人费解。第二条语句的工作原理除了它跳过else块之外。混乱,特别是对Python(但不是编码)的新手。 – DeeDee
在这种特殊情况下,为什么不把语句放入try块中。根据http://stackoverflow.com/questions/855759/python-try-else你唯一需要的其他时间是当有异常引发的情况下,你不想被你的除外:在这种情况下,否则不需要。 – sabbahillel