Package library :: Package pyjamas :: Module PyExternalMod
[hide private]
[frames] | no frames]

Source Code for Module library.pyjamas.PyExternalMod

 1  from pyjamas.JSONService import JSONProxy 
 2  from pyjamas.HTTPRequest import HTTPRequest 
 3  from __pyjamas__ import JS 
4 5 -class PyjamasExternalProxy(JSONProxy):
6 singleton = None 7
8 - def __init__(self):
9 JSONProxy.__init__(self, "/obj/handler", ["call","methods"], True)
10 11 @staticmethod
12 - def instance():
16
17 18 -class PyjamasExternalModule:
19 PyjamasExternalModule.http = HTTPRequest() 20
21 - def __init__(self, mod_name):
22 self.base = 'http://'+JS('''__location['host']''') 23 req = '{"method":"methods","params":["%s"],"id":1}'%(mod_name) 24 res = PyjamasExternalModule.http.syncPost(self.base+'/obj/handler',req) 25 self.methods = self.__parseJSON(res)['result'] 26 self.module = mod_name 27 28 for method in self.methods: 29 self.__createMethod(method)
30
31 - def __encodeJSON(self, obj):
32 JS(''' 33 var t = typeof(@{{obj}}); 34 if(@{{obj}}==null) { 35 return 'null'; 36 }else if(t=='number') { 37 return ''+@{{obj}}; 38 }else if(t=='string'){ 39 return '"'+@{{obj}}+'"' 40 }else if(@{{isinstance}}([@{{obj}},@{{list}}],{})) { 41 var parts = []; 42 for(var i=0; i<@{{obj}}['length']; i++) { 43 parts['append']([ @{{self}}['__encodeJSON']([@{{obj}}[i]],{}) ],{}); 44 } 45 return "[" + ','['join']([parts],{}) + "]"; 46 }else{ 47 throw "Dicts and Objectss can not be jsoned !"; 48 } 49 ''')
50
51 - def __parseJSON(self, str):
52 JS(r""" 53 try { 54 return (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(@{{str}})) && 55 eval('(' + @{{str}} + ')'); 56 } catch (e) { 57 return false; 58 } 59 """)
60
61 - def __createMethod(self, method):
62 def inner(*args, **kargs): 63 params = self.__encodeJSON(args) 64 req = '{"method":"call","params":["%s", "%s", %s],"id":2}'%(self.module,method,params) 65 res = PyjamasExternalModule.http.syncPost(self.base+'/obj/handler',req) 66 return self.__parseJSON(res)['result']
67 JS(""" 68 @{{self}}[@{{method}}] = @{{inner}}; 69 """)
70