2016-11-03 4 views
0

私はサーバにリクエストを送信し、レスポンスを受け取ります。状況によってはレスポンスが異なるため、それぞれの処理方法が異なります。異なるサーバレスポンスをエレガントに扱う

私は何をしたいのは、この種のものを持っている:

if response.getChild('child1')... == x: 
    do_math() 
    return stuff1 
elif response.getChild('child2')... == y 
    do_different_math() 
    return stuff2 
etc... 

しかし、私は私が複数のtry-除いを使用する必要がありますされ、別の子供が存在しない可能性があることを問題に実行していますフロー制御。これは多くのスペースを必要とし、ひどく醜いです:

try: 
    if response.getChild('child1')... == x: 
     do_math() 
     return message1 
except: 
    return generic_error_message 
try: 
    if response.getChild('child2')... == y: 
     do_different_math() 
     return stuff2 
except: 
    return generic_error_message 
etc... 

異なる可能な対応を扱うエレガントな方法はありますか?

+0

[ 'GET']( Python辞書のhttps://docs.python.org/2/library/stdtypes.html#dict.get)メソッドには、期待値が見つからない場合にデフォルト値を提供するという面白い動作があります。 'getChild'メソッドのドキュメントを見て、それが[mapping](https://docs.python.org/3/glossary.html#term-mapping)オブジェクトでないかどうかを確認してください。もしそうなら、あなたは 'response.getChild( 'child2'、None)'のようなアプローチを使い、 'None'resultで処理することができます。 –

答えて

0

懸念事項を分けることをお勧めします。あなたは効果的にしたい:

  • 例外
  • を上げることができる応答を取得するには、応答

の値に基づいて操作を実行する応答を得るためのプロセスは、に例外が発生することがありあなたが探している子供が存在しないかもしれないので、育てられます。あなたのコードはすべての例外をキャッチしますが、特定の例外をキャッチするようにしてください。子が存在しない場合は、操作を実行する必要はありません。あなたが複数のノード(子供)を反復処理する必要があるため

# define a function to return the right 
# operation to perform based on response 
# obviously the methods do_math and do_different_math must be defined 
# as well as x and y 
def what_to_do(val): 
    if val == x: 
     return do_math 
    elif val == y: 
     return do_different_math 
    else: 
     raise ValueError("Unknown value %r. I don't know what to do" % val) 

# Do something to get the node that you want 
# here is just set the value to 'child1' for 
# demonstration purposes 
node = 'child1' 
result = None 
answer = None 

try: 
    result = response.getChild(node) 
except SOMES_SPECIFIC_EXCEPTION: 
    # you need to decide what to do here 
    pass 

if result is not None: 
    operation = what_to_do(result) 
    answer = operation() 
return answer 

:私のようなものをお勧めします。 forループにコードを配置することができます。

+0

「必要なノードを取得するための何か」は、複数の「try:except:」セグメントを実行する問題です。 理想的には、応答なし。他のすべてのケースでは、特定のノードがあるかどうかをチェックしていますが、ifステートメントでそれをやりたいのですが、そうでないと、次の節に渡すのではなくエラーが発生するためです。 – JohnnyQ

0

responseresponse.getChild()のような文脈を与えないと、getChild()がどのような例外を発生させる可能性があり、どのように実際に処理されるはずですか?また、いくつかの条件に応じた処理のディスパッチとユーザへのメッセージの発行という、別個の懸案事項を混在させているように見えます。とにかく

:醜い繰り返さ/コードは、テスト及び処理し、この配列上、ループの両方をカプセル化するオブジェクトの配列を構築することで回避する1つの方法、すなわち:

class Action(object): 
    def __init__(self, accept, run, message): 
     self.accept = accept 
     self.run = run 
     self.message = message 


actions = [ 
    Action(lambda r: r.getChild("child1") == x, do_math, some_message), 
    Action(lambda r: r.getChild("child2") == y, do_different_math, some_other_message), 
    ] 

def dispatch(response, actions): 
    for action in actions: 
     try: 
      if action.accept(response): 
       action.run() 
       return action.message 
     except SomeExpectedException as e: 
      return generic_error_message 
関連する問題