diff options
author | 2013-06-09 18:10:22 +0200 | |
---|---|---|
committer | 2013-06-09 18:10:23 +0200 | |
commit | 16af85004c84d0d6c626b4f8424ce9647669a0c1 (patch) | |
tree | 025d479862d376dbc17e934f4ed20031c8cd97d1 /pyload/remote/WSClient.py | |
parent | adapted to jshint config (diff) | |
download | pyload-16af85004c84d0d6c626b4f8424ce9647669a0c1.tar.xz |
moved everything from module to pyload
Diffstat (limited to 'pyload/remote/WSClient.py')
-rw-r--r-- | pyload/remote/WSClient.py | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/pyload/remote/WSClient.py b/pyload/remote/WSClient.py new file mode 100644 index 000000000..793a6ef28 --- /dev/null +++ b/pyload/remote/WSClient.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from websocket import create_connection +from httplib import UNAUTHORIZED, FORBIDDEN + +from json_converter import loads, dumps +from apitypes import Unauthorized, Forbidden + +class WSClient: + URL = "ws://localhost:7227/api" + + def __init__(self, url=None): + self.url = url or self.URL + self.ws = None + + def connect(self): + self.ws = create_connection(self.URL) + + def close(self): + self.ws.close() + + def login(self, username, password): + if not self.ws: self.connect() + return self.call("login", username, password) + + def call(self, func, *args, **kwargs): + if not self.ws: + raise Exception("Not Connected") + + if kwargs: + self.ws.send(dumps([func, args, kwargs])) + else: # omit kwargs + self.ws.send(dumps([func, args])) + + code, result = loads(self.ws.recv()) + if code == 400: + raise result + if code == 404: + raise AttributeError("Unknown Method") + elif code == 500: + raise Exception("Remote Exception: %s" % result) + elif code == UNAUTHORIZED: + raise Unauthorized() + elif code == FORBIDDEN: + raise Forbidden() + + return result + + def __getattr__(self, item): + def call(*args, **kwargs): + return self.call(item, *args, **kwargs) + + return call + +if __name__ == "__main__": + api = WSClient() + api.login("User", "test") + print api.getServerVersion()
\ No newline at end of file |