diff --git a/src/main.py b/src/main.py index 159b5f9..cbf17b1 100755 --- a/src/main.py +++ b/src/main.py @@ -4,14 +4,28 @@ from twitch import TwitchClient import json +import cherrypy + +class FleastServer(object): + def __init__(self): + try: + with open('.token', 'r') as reader: + twitch_token = reader.read().strip() + except: + print("Cannot read token for twitch app, abort.") + exit(1) + client = TwitchClient(twitch_token, freq = 1) + + @cherrypy.expose + def index(self): + return 'Hello World' + + @cherrypy.expose + def fleast(self, game, lang): + return game def main(): - with open('.token', 'r') as reader: - twitch_token = reader.read().strip() - - client = TwitchClient(twitch_token) - r = client.raw_query_v5('streams/?game=IRL&language=ru&limit=2') - print(json.dumps(r, indent=4)) + cherrypy.quickstart(FleastServer()) if __name__ == '__main__': diff --git a/src/server.conf b/src/server.conf new file mode 100644 index 0000000..c480dbc --- /dev/null +++ b/src/server.conf @@ -0,0 +1,2 @@ +[global] +server.socket_port: 8080 diff --git a/src/twitch.py b/src/twitch.py index 80c815f..8c587c6 100644 --- a/src/twitch.py +++ b/src/twitch.py @@ -18,13 +18,17 @@ class TwitchClient: def do_q(self, base, header): self.lock.acquire() - delta = time.time() - self.last_q - if delta < self.delay: - time.sleep(delta) - r = requests.get(base, headers=header).json() - self.last_q = time.time() - self.lock.release() - return r + try: + delta = time.time() - self.last_q + if delta < self.delay: + time.sleep(delta) + r = requests.get(base, headers=header).json() + self.last_q = time.time() + except: + r = None + finally: + self.lock.release() + return r def get_base(self, ver): if ver == 'v5': return (self.header_v5, self.urlbase_v5) @@ -45,7 +49,7 @@ class TwitchClient: def get_game_id(self, name): header, base = self.get_base('v5') r = self.do_q('%s/search/games?query=%s' % (base, name), header) - if r.get('games', None): return (r['games'][0]['_id'], r['games'][0]['name']) + if r and r.get('games'): return (r['games'][0]['_id'], r['games'][0]['name']) return None def get_game_list(self, name, lang, lim):