Commits

Anonymous committed 44cb5c4

first running doctest

Comments (0)

Files changed (4)

franziska/api/base.py

 from tornado import httpclient
 import weakref
 import logging
-
-import adisp
+from client import TornadoClient
+import copy
 
 #TODO: after doctest add serious documentation
 #build method map as objects - todo analyse repetition
 method_map = Method(".",
         childs = [version_map, users_map,roles_map,
             catalogs_map, processes_map,
+            repo_map, #for root catalog
             Method("reconfigure", allowed = ["POST"]),
             Method("reopenLog", allowed = ["POST"]),
             Method("initfile", disallowed = ["POST"]),
         #self._io_loop.start()
         self._command_map = self.build_command_map(self, self.url, method_map)
         self.version.read()
+        return True
 
     def close(self):
         """close all client connections"""
         
         #print "\t"* tab, method_map.name    
         for child in method_map.childs:
-            cmd_map[child.name] = Dispatcher(db, url, child.name)
+            cmd_map[child.name] = Dispatcher(db, url, child.name, auth = self.auth)
             childs = self.build_command_map(db, "%s/%s"%(url, child.name),
                         child, tab+1)
             cmd_map[child.name].add_childs(childs)
 class CMD(TornadoClient):
     default_headers = {"Content-type": "application/json",
                        "Accept": "application/json"}
-    def __init__(self, conn, url,cmd):
+    def __init__(self, conn, url, cmd, io_loop = None):
         self._conn = conn
         self.cmd = cmd
         self.url =  "%s/%s" %(url, cmd)
         self._response = -1
-        super(CMD, self).__init__()
+        super(CMD, self).__init__() #init client
 
 #TODO: refactor it
     def build_cmd(self, method):
                 local_headers = kwargs.pop("headers")
             except:
                 local_headers = self.default_headers
-            
+
             request = self.__build_request(method = method.upper(),
                                            headers = local_headers, **kwargs)
             self.requests.append(request)
-            return self.run(request)
+            return self.run()
         return executor
 
     def __build_request(self, **kwargs):
             url = kwargs.pop("url")
         else:
             url = self.url
+        
         request = httpclient.HTTPRequest(url = url, **kwargs)
         return request
 
         self.name = name #name of selected data
         self._db = db
         self.auth = auth if auth else self._db.auth
+
+        #TODO: refactor this part to inheritance
         self.cmd_obj = CMD(self._db._conn, url, cmd) #auth is here pointless - hard coded
-        #TODO: rewrite to accept Method allow and decline values
-        self._read =  self.cmd_obj.build_cmd("GET")
-        self._create = self.cmd_obj.build_cmd("POST")
-        self._update = self.cmd_obj.build_cmd("UPDATE")
-        self._delete = self.cmd_obj.build_cmd("DELETE")
+        self.update_wrappers()
+
         self.parent = parent #TODO:weakref
         self.childs = {} #TODO:weakref.WeakKeyDictionary()
         if childs:
             self.add_childs(childs)
 
+    def update_wrappers(self):
+        self._read =  self.cmd_obj.build_cmd("GET")
+        self._create = self.cmd_obj.build_cmd("POST")
+        self._update = self.cmd_obj.build_cmd("UPDATE")
+        self._delete = self.cmd_obj.build_cmd("DELETE")
     #TODO: add __getattr that supports childs
     def add_childs(self, childs):
         if isinstance(childs, list):
         else:
             raise ValueError, "add_childs accepts only list or dict values"
 
+    
+    def get_auth(self):
+        return self.auth
+
+    def get_url(self):
+        return self.cmd_obj.url
+
     #initialize proxy object.
-    def init_new(self, name):
+    def init_new(self,name):
         """
         Initialize copy, but didnt use copy() to prevent some
         anormality
         """
-        url = "%s/%s" %(self.cmd_obj.url, self.name)
-        obj = Dispatcher(self._db, url,  name,
+        obj = Dispatcher(self._db, self.get_url(), cmd = name, name = name,
                 parent = self, childs = self.childs, auth = self.auth)
+
         return obj
         
     #TODO: Its broken - it puts authenification to everywhere
     def __add_auth(self, **kwargs):
         """monkey patching basic authentification """
-        print "adding authentification params"
-        if self.auth:
-            kwargs.update({"auth_username": self.auth[0],
-                            "auth_password": self.auth[1]})
-            print "added authentification", kwargs
+        if len(kwargs) == 0:
+            kwargs = {}
+
+        kwargs.update({"auth_username": self.auth[0],
+                        "auth_password": self.auth[1]})
+        return kwargs
+            
 
     def read(self, refresh = False, **kwargs):
         if self.data is None or refresh == True:
-            self.__add_auth(**kwargs)
-            print kwargs
+            #fetch or reload data
+            kwargs = self.__add_auth(**kwargs)
             self.data = self._read(**kwargs)
         return self.data
 
     def create(self, **kwargs):
-        self._add_auth(**kwargs)
+        kwargs = self.__add_auth(**kwargs)
         val = self._create(**kwargs) #gets response code
         #refresh data list
         self.read()
         return val
 
     def update(self, **kwargs):
-        self._add_auth(**kwargs)
+        kwargs = self.__add_auth(**kwargs)
         val = self._update(**kwargs) #returns response code
         #renew datalist
         self.read()
             NB! it doesnt object from self.data, but refreshes values
             from server, to guarantee success of all process
         """
-        self._add_auth(**kwargs)
+        kwargs = self.__add_auth(**kwargs)
         val = self._delete(**kwargs)
         self.read()
         return val
 
     def __getitem__(self, item):
         """add dict interface to Dispatcher object """
-        if item in self.data:
+        exists = [True for x in self.data if x['id'] == item]
+        if exists[0] == True:
             new_obj = self.init_new(item)
+            new_obj.name  = item
             return new_obj
         else:
-            raise KeyError, "%s dont have key %s" % (self.__class__.__name__,
-                    str(item))
+            raise KeyError, "%s dont have key %s" % (
+                self.__class__.__name__, str(item))
 
     def __delitem__(self, item):
         try:
     def __getattr__(self, cmd_name):
         """ to access subcommands as class property """
         try:
-            return self.childs[cmd_name]
+            child = self.childs[cmd_name]
+            if self.name:
+                #if parent name is specified,then make 
+                #copy object because it will be temporary as like parent is actually proxy
+                #and overrun some values
+                child = copy.copy(child)
+                child.parent = self
+                child.cmd_obj = CMD(self._db._conn, self.get_url(), cmd_name)
+                child.update_wrappers()
+
+            return child
         except:
             raise KeyError, "Dispatcher dont have child cmd: %s" % str(cmd_name)
+    
+    
+    def __call__(self, name = None, refresh = False):
+        if name:
+            #add proxy object
+            proxy = self.init_new(name)
+            val = proxy.read()
+        else:
+            val = self.read(refresh)
+        return val

franziska/api/client.py

 import tornado.web
 import tornado.httpclient
 
+import simplejson
 import functools
 
-import adisp
-
 class BaseClient(object):
     '''
     Baseclass for webclients
 
     def run(self):
         """public method to run requests"""
-        self.__worker()
-        return self.True
+        return self.__worker()
 
     def __worker(self):
-        print "worker"
         for request in self.requests:
             self.__fetch(request)
+        
+        return self.responses
 
 
     def __fetch(self, request, callback = None):
         def handle_request(response):
             if response.error:
-                self.responses.append({"Error": response.error})
+                self.responses.append({"error": response.error,
+                                        "url":  response.request.url,
+                                        "header": response.request.headers,
+                                        "auth": response.request.auth_username})
             else:
-                self.responses.append(response.body)
+                if response.headers['Content-Type'].find("json") > 0:
+                    #if returned values are in json, then parse it
+                    val = simplejson.loads(response.body)
+                    if isinstance(val, list):
+                        self.responses.extend(val)
+                    else:
+                        self.responses.append(val)
+                else:
+                    self.responses.append(response.body)
             self._io_loop.stop()
 
         client = tornado.httpclient.AsyncHTTPClient(io_loop = self._io_loop)
 import gevent
 from gevent import monkey
 
+
+
 import urllib2
 class GeventClient(BaseClient):
     def __init__(self, requests = None):

franziska/api/test/base_doc.py

 
 #Init database
 >>> from base import *
->>> db = Franziska(auth = ("timgluz", "baas471"))
+>>> db = Franziska(auth = ("root", "baas471"))
 >>> db.connect()
->>> db.version.read()
-'4.2'
+True
+>>> db.version()
+['4.2']
+
+#full path to read vals of catalog
+>>> db.catalogs.read() # doctest:+ELLIPSIS
+[...]
+
+#shortcut to read vals of catalog
+>>> db.catalogs() # doctest: +ELLIPSIS
+[...]
+
+>>> db.repositories.read() #doctest: +ELLIPSIS
+[...]
+
+>>> db.repositories.data[0] == db.repositories()[0]
+True
+
+>>> db.repositories['test'].get_url()
+'http://192.168.100.5:10035/repositories/test'
+
+>>> db.repositories['test'].size.parent.name
+'test'
+
+>>> db.repositories['test'].size.get_url()
+'http://192.168.100.5:10035/repositories/test/size'
+
+>>> db.repositories['test'].size.get_auth()
+('root', 'baas471')
+
+>>> db.repositories['test'].size()
+
+>>> db.close()
 
 """

franziska/api/test/base_doc.pyc

Binary file modified.