forked from pyload/pyload
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSONClient.py
More file actions
56 lines (45 loc) · 1.62 KB
/
JSONClient.py
File metadata and controls
56 lines (45 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from urllib import urlopen, urlencode
from httplib import UNAUTHORIZED, FORBIDDEN
from json_converter import loads, dumps
from apitypes import Unauthorized, Forbidden
class JSONClient:
URL = "http://localhost:8001/api"
def __init__(self, url=None):
self.url = url or self.URL
self.session = None
def request(self, path, data):
ret = urlopen(self.url + path, urlencode(data))
if ret.code == 400:
raise loads(ret.read())
if ret.code == 404:
raise AttributeError("Unknown Method")
if ret.code == 500:
raise Exception("Remote Exception")
if ret.code == UNAUTHORIZED:
raise Unauthorized()
if ret.code == FORBIDDEN:
raise Forbidden()
return ret.read()
def login(self, username, password):
self.session = loads(self.request("/login", {'username': username, 'password': password}))
return self.session
def logout(self):
self.call("logout")
self.session = None
def call(self, func, *args, **kwargs):
# Add the current session
kwargs["session"] = self.session
path = "/" + func + "/" + "/".join(dumps(x) for x in args)
data = dict((k, dumps(v)) for k, v in kwargs.iteritems())
rep = self.request(path, data)
return loads(rep)
def __getattr__(self, item):
def call(*args, **kwargs):
return self.call(item, *args, **kwargs)
return call
if __name__ == "__main__":
api = JSONClient()
api.login("User", "test")
print api.getServerVersion()