2

だから私はDjangoが素晴らしいメッセージフレームワークを持っていることに気づきました。5つの異なるレベル(情報、エラー、デバッグ、警告、および成功)があります。

例外をビューレベルまで伝播し、これらの例外のいくつかを報告するのは本当に素晴らしいことです。

lib.py

def read_file(user, filename, **kwargs):
   try:
     with open(...):
        return f.read()
   except Exception, e:
     raise e

utli.py

def wrapper_read_file(user, filename, **kwargs):
   try:
      if user.is_authenticated and user.belongs('admin'):
          lib.read_file(...)
      else:
          raise Exception("Unauthenticated user!!!")
   except Exception, e:
      raise e

views.py

def my_view(request):
   [..] do something here
   try:
     result = wrapper_read_file(...)
     return render(request, 'hello.html', {'result': result})
   except Exception, e:
     if isinstance(e, IOError):
         if e.errno==errno.ENOENT:
         messages.add_message(request, message.ERROR, 'File does not exist.')
     elif isinstance(e, OSError):
         messages.add_message(request, message.ERROR, 'You don't have sufficient permission to open the file.')
     return render(request, 'hello.html', {'hello_world': 'hello_world'}

Djangoはレンダリングの方法を知っておりmessages、私にはそれを行う機能があります。したがって、が表示されますmessages

私の例外処理は合理的に見えると思いますか?別の提案はありますか?私はPythonエラー例外処理にかなり慣れていません。

4

1 に答える 1

2

おそらく、すべての例外をキャッチしたくないでしょう。これにより、他のエラーがマスクされる可能性があり、Ctrl-Cが機能しなくなるなどの処理が行われます。代わりに、処理する例外のみをキャッチします。

try:
    # action that may throw an exception
except IOError, e: # Will only catch IOErrors
    if e.errno == errno.ENOENT:
        messages.add_message(request, messages.ERROR, "File not found")
    else:
        raise e    # Re-raise other IOErrors
except OSError, e: # Will only catch OSErrors
    messages.add_message(request, messages.ERROR, "Insufficient permissions")

return render(request, 'hello.html', {})

更新:他の別の例外タイプを処理するための2番目のexcept句を追加しました。これは、すべて OSErrorsがアクセス許可に関連しているという(大きな)仮定を行うため、おそらくまだ不十分であることに注意してください。

于 2012-06-05T11:21:04.740 に答える