-
Notifications
You must be signed in to change notification settings - Fork 0
/
autolib.py
87 lines (72 loc) · 2.61 KB
/
autolib.py
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import imp, os, parser, tempfile, re, urllib2
from urllib import urlencode
AUTOLIB_SERVER = 'http://ianab.com/autolib/'
lib_re = '[a-z][\w\-\.]*'
def get_url(url, data=None):
try:
result = urllib2.urlopen(url, data=data)
except urllib2.HTTPError, result:
pass
return result.code, result.read()
class ServerStore(object):
def get_src(self, name):
url = self.url + 'lib/' + name + '/'
code, content = get_url(url)
if code == 404:
raise AttributeError, 'Library not found.'
elif code != 200:
raise Exception, 'The server could not handle your request.'
else:
return content
def set_src(self, name, src):
url = self.url + 'lib/' + name + '/'
data = urlencode({'src': src})
code, content = get_url(url, data)
if code == 403:
raise ValueError, "Library with that name already exists."
elif code != 200:
raise Exception, 'The server could not handle your request.'
def list_modules(self):
url = self.url + 'list/'
code, content = get_url(url)
if code == 500:
raise Exception, 'The server could not handle your request.'
return content.split()
def __init__(self, url=AUTOLIB_SERVER):
self.url = url
class Autolib(object):
def _make_module(self, name, src):
fd, path = tempfile.mkstemp(suffix='.py')
f = os.fdopen(fd, 'w')
f.write(src)
f.close()
return imp.load_source(name, path)
def __getattr__(self, modname):
if modname in self._module_cache:
return self._module_cache[modname]
src = self._store.get_src(modname)
mod = self._make_module(modname, src)
self._module_cache[modname] = mod
return mod
def __setattr__(self, name, val):
if name.startswith('_'):
return object.__setattr__(self, name, val)
if not re.match(lib_re, name):
raise ValueError, "Invalid library name."
path = val.__file__
if path.endswith('.pyc'):
path = path[:-1]
if not path.endswith('.py'):
raise ValueError, 'Module must be a .py file'
src = open(path).read()
try:
parser.suite(src)
except (TypeError, SyntaxError, parser.ParserError):
raise ValueError, 'Module does not parse correctly.'
self._store.set_src(name, src)
def List(self):
return self._store.list_modules()
def __init__(self, store=ServerStore()):
self._module_cache = {}
self._store = store
autolib = Autolib()