2014-02-27 36 views
3

我使用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) 
+0

我已经做了一个快速测试,'>>>试试: ......通过 ...除了: ......通过 ...别的: ...打印 '其他' ...终于: ...打印'终于' ... 其他 终于 '这似乎工作。必须有别的东西。 – njzk2

+0

@ njzk2对,因为第一个陈述完全按照它应该的方式工作,所以都令人费解。第二条语句的工作原理除了它跳过else块之外。混乱,特别是对Python(但不是编码)的新手。 – DeeDee

+0

在这种特殊情况下,为什么不把语句放入try块中。根据http://stackoverflow.com/questions/855759/python-try-else你唯一需要的其他时间是当有异常引发的情况下,你不想被你的除外:在这​​种情况下,否则不需要。 – sabbahillel

回答

2

我觉得没有定义errors

len(errors)将引发异常,但不能防止finally块的执行,因此,仍然将一些数据,而不必定义result_response['success']

+0

谢谢:我用else测试了这个:print'in else',错误,'out of else'最后:'done'和'in else''已完成'后面跟着NameError错误未定义的输出。 – sabbahillel

+0

错字在上面的评论,每个字符串应该有一个单独的打印它是不可遏制的,你可能想要添加一个代码片段来说明你的观点。 – sabbahillel

3

如果else块中引发一个例外,它被忽略,因为解释器从该功能执行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不会导致任何回溯。

+0

,它使得'return'和'finally'的使用相当危险,因为没有理由如果在except块中引发异常,结果也不会有任何不同。 – njzk2

+0

这是正确的和有帮助的,谢谢! @ njzk2先发现错误,所以我想我必须给他支票。 – DeeDee

相关问题