Esempio n. 1
0
    def wait_once(self, cb=None, **params):
        if cb is not None:
            check_callable(cb)

        params.update({"feed": "longpoll"})
        resp = self.db.res.get("_changes", **params)
        
        with resp.body_stream() as body:
            sock = self.patch_socket(body.reader.unreader.sock)
            body.reader.unreader.sock = sock
            try:
                while True:
                    if self.wait_read(sock):
                        buf = []
                        while True:
                            chunk = body.read()
                            if not chunk:
                                break
                            buf.append(chunk)

                        if cb is not None:
                            self.spawn(self.handle, cb, "".join(buf))
                            self.sleep(0.1)
                        else:
                            ret = "".join(buf)
                            try:
                                return json.loads(ret)
                            except ValueError:
                                return ret
                        break
            except NoMoreData:
                pass
            except (SystemExit, KeyboardInterrupt):
                pass
Esempio n. 2
0
 def consume(self, resp):
     with resp.body_stream() as body:
         buf = []
         while True:
             data = body.read()
             if not data:
                 break
             buf.append(data)
         change = "".join(buf)
         try:
             change = json.loads(change)
         except ValueError:
             pass 
         self.process_change(change)
Esempio n. 3
0
    def wait_once(self, cb=None, **params):
        if cb is not None:
            check_callable(cb)

        params.update({"feed": "longpoll"})
        resp = self.db.res.get("_changes", **params)
        buf = ""
        with resp.body_stream() as body:
            while True:
                data = body.read()
                if not data: 
                    break
                buf += data
            
            ret = json.loads(buf)
            if cb is not None:
                cb(ret)
                return

            return ret
Esempio n. 4
0
 def wait_once(self, **params):
     """Wait for one change and return (longpoll feed) 
     
     Args:
     @param params: kwargs
     See Changes API (http://wiki.apache.org/couchdb/HTTP_database_API#Changes)
     
     @return: dict, change result
     """
     params.update({"feed": "longpoll"})
     resp = self.db.res.get("_changes", **params)
     buf = ""
     with resp.body_stream() as body:
         while True:
             data = body.read()
             if not data: 
                 break
             buf += data
         
         ret = json.loads(buf)
         for callback in self.callbacks:
             callback(ret)
         return ret
Esempio n. 5
0
 def emit_line(self, line):
     line = json.loads(line)
     for callback in self.callbacks:
         callback(line)
Esempio n. 6
0
 def emit_line(self, line):
     line = json.loads(line)
     self.callback(line)
Esempio n. 7
0
    def request(self, method, path=None, payload=None, headers=None, **params):
        """ Perform HTTP call to the couchdb server and manage 
        JSON conversions, support GET, POST, PUT and DELETE.
        
        Usage example, get infos of a couchdb server on 
        http://127.0.0.1:5984 :


            import couchdbkit.CouchdbResource
            resource = couchdbkit.CouchdbResource()
            infos = resource.request('GET')

        @param method: str, the HTTP action to be performed: 
            'GET', 'HEAD', 'POST', 'PUT', or 'DELETE'
        @param path: str or list, path to add to the uri
        @param data: str or string or any object that could be
            converted to JSON.
        @param headers: dict, optional headers that will
            be added to HTTP request.
        @param raw: boolean, response return a Response object
        @param params: Optional parameterss added to the request. 
            Parameterss are for example the parameters for a view. See 
            `CouchDB View API reference 
            <http://wiki.apache.org/couchdb/HTTP_view_API>`_ for example.
        
        @return: tuple (data, resp), where resp is an `httplib2.Response` 
            object and data a python object (often a dict).
        """
        
        headers = headers or {}
        headers.setdefault('Accept', 'application/json')
        headers.setdefault('User-Agent', USER_AGENT)

        if payload is not None:
            #TODO: handle case we want to put in payload json file.
            if not hasattr(payload, 'read') and not isinstance(payload, basestring):
                payload = json.dumps(payload).encode('utf-8')
                headers.setdefault('Content-Type', 'application/json')

        params = encode_params(params)
        try:
            resp = Resource.request(self, method, path=path,
                             payload=payload, headers=headers, **params)
                             
        except ResourceError, e:
            msg = getattr(e, 'msg', '')
            if e.response and msg:
                if e.response.headers.get('content-type') == 'application/json':
                    try:
                        msg = json.loads(msg)
                    except ValueError:
                        pass
                    
            if type(msg) is dict:
                error = msg.get('reason')
            else:
                error = msg
                
            if e.status_int == 404:
                raise ResourceNotFound(error, http_code=404,
                        response=e.response)

            elif e.status_int == 409:
                raise ResourceConflict(error, http_code=409,
                        response=e.response)
            elif e.status_int == 412:
                raise PreconditionFailed(error, http_code=412,
                        response=e.response)
            else:
                raise
Esempio n. 8
0
 def json_body(self):
     try:
         return json.loads(self.body_string())
     except ValueError:
         return self.body_string()
Esempio n. 9
0
 def lines(self):
     line = self.stdin.readline()
     while line:
         yield json.loads(line)
         line = self.stdin.readline()
Esempio n. 10
0
 def handle(self, cb, line):
     try:
         line = json.loads(line)
     except ValueError:
         pass
     cb(line)