0

私はPython用のオープンソースのtwitch.tvAPIラッパーを作成していますが、これまでのところ次のようになっています。

import urllib2
import json
import time
waittime = 1
baseurl = 'https://api.twitch.tv/kraken/'

class twitchchannelinfo():
    def __init__ (self,channel):
        self.channel = channel
        time.sleep(waittime)
        self.dict1 = json.loads(urllib2.urlopen(baseurl + 'channels/' + channel).read())

    def getstatus(self):
        return self.dict1 ['status']
    def getdisplay_name(self):
        return self.dict1 ['display_name']
    def getmature(self):
        return self.dict1 ['mature']
    def getchanurl(self):
        return self.dict1 ['url']
    def getcreated_at(self):
        return self.dict1 ['created_at']
    def getteams(self):
        return self.dict1 ['teams']
    def getgame(self):
        return self.dict1 ['game']
    def getupdated_at(self):
        return self.dict1 ['updated_at']

このAPIにエラーチェックを追加したいと思います。サーバーは、エラーに対して次のようなjson応答を返します。

{
    "error": "Unprocessable Entity",
    "status": 422,
    "message": "Channel 'deeman' is not available on Twitch"
}

次に、を使用して辞書に変換しjson.loadsます。この辞書で値「エラー」を確認するにはどうすればよいですか、またはこれを行うためのより良い方法はありますか?

4

3 に答える 3

2

私はすることをお勧めします:

if 'error' in self.dict1:
    raise ValueError("%s: %s" % (self.dict1["error"], self.dict1["message"]))
于 2013-03-12T17:41:38.883 に答える
0
if 'error' in self.dict1:
  # do blah
于 2013-03-12T17:38:22.033 に答える
0
try:
    self.dict1[u'error']
except KeyError:
    ## Do something here

これは、tryを使用した別のアプローチです...

于 2013-03-12T17:41:00.600 に答える