~ampernand/anonplus/i2p_branch

« back to all changes in this revision

Viewing changes to src/api/__init__.py

  • Committer: Aj00200
  • Date: 2012-05-21 21:34:51 UTC
  • Revision ID: aj00200@aj00200.org-20120521213451-a7zmyptcqm32c5xx
Moved and reduced the API module. Modules will now be imported directly and run in their own thread.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
import socket
2
 
import json
3
 
 
4
1
import sys
5
2
 
6
 
def read(socket, size):
7
 
    size = int(size)
8
 
    datareturn = ""
9
 
        
10
 
    while len(datareturn) < size:
11
 
        try:
12
 
            datareturn += socket.recv(1)
13
 
        except IOError:
14
 
            return datareturn
15
 
 
16
 
    return datareturn
17
 
 
18
 
 
19
 
 
20
 
class _Method:
21
 
    def __init__(self,socket, funcname):
22
 
        self.func = funcname
23
 
        self.socket = socket
24
 
 
25
 
    def __call__(self,*args,**kwargs):
26
 
        self.req = self._make_request(self.func, *args,**kwargs)
27
 
        self.socket.send(self.req)
28
 
        length = int(read(self.socket, 4))
29
 
 
30
 
        return json.loads(read(self.socket, length))
31
 
 
32
 
    def _make_request(self, func, *args, **kwargs):
33
 
 
34
 
        request = {}
35
 
        request["function"] = func
36
 
        request["args"] = args
37
 
        request["kwargs"] = kwargs
38
 
 
39
 
 
40
 
        js = json.dumps(request)
41
 
        size = len(js)
42
 
        req = "%4i%s" % (size, js)
43
 
        return req
44
 
 
45
 
class VomunAPI:
46
 
    def __init__(self,server="127.0.0.1", port=3451):
47
 
        self.socket = socket.socket()
48
 
        self.socket.connect((server, port))
49
 
 
50
 
    def __getattr__(self, name):
51
 
        # magic method dispatcher
52
 
        return _Method(self.socket, name)
53
 
    
54
 
class APIApp:
 
3
class App:
55
4
    '''A class which privides overwritable methods to included apps.'''
56
5
    def setup(self):
57
6
        '''Called when the app is loaded.'''
58
7
        pass
59
8
    
60
 
def register_app(app):
 
9
def register(app):
61
10
    '''Registers the app as being loaded, and creates and stores the instance
62
11
    to send events to. Also calls the setup method on the app object once it
63
12
    is created from the provided class. `app` should be a class.
65
14
    instance = app()
66
15
    # TODO: register instance
67
16
    instance.setup()
68
 
    
69
 
    
70
 
api = VomunAPI()
71
 
 
72
 
if __name__ == '__main__':
73
 
    print api.__getattr__(sys.argv[1])(*sys.argv[2:])
74
 
    #print api.__getattr__(sys.argv[1])()
75
 
 
76
 
    #print api.get_functions()