예제 #1
0
 def test_fetch(self):
     # add a database without http auth
     client = CouchAsyncHTTPClient('http://172.16.200.51:5984/', self.io_loop)
     resp = yield client.fetch(
         'newcmdb',
         method="PUT",
         raise_error=False,
         allow_nonstandard_methods=True
     )
     self.assertEqual(resp.body, '{"error":"unauthorized","reason":"You are not a server admin."}')
예제 #2
0
 def test_fetch_del(self):
     # delete a database with http auth
     client = CouchAsyncHTTPClient('http://172.16.200.51:5984/', self.io_loop)
     resp = yield client.fetch(
         'newcmdb',
         method="DELETE",
         raise_error=False,
         auth_username='******',
         auth_password='******',
         allow_nonstandard_methods=True
     )
     self.assertEqual(resp.body, '{"ok":true}\n')
예제 #3
0
파일: orm.py 프로젝트: liuyangc3/cmdb
class CouchServer(object):
    """
    couchdb database operation
    """

    def __init__(self, url='http://localhost:5984', io_loop=None):
        self.base_url = url[:-1] if url.endswith('/') else url
        self.io_loop = io_loop or ioloop.IOLoop.instance()
        self.client = CouchAsyncHTTPClient(self.base_url, self.io_loop)

    @gen.coroutine
    def create(self, database):
        # if couchdb set a admin must use http auth to create/delete a database

        # because tornado AsyncHttpclient can not send a empty body with 'PUT' method
        # so here set allow_nonstandard_methods = True
        # this option send body with a '0' instead of empty
        # if couchdb implement on a windows client will get an error: [Errno 10054]
        # because couchdb send a RST packet , but it works fine on Linux
        try:
            resp = yield self.client.fetch(
                database,
                method="PUT",
                auth_username=couch_conf['user'],
                auth_password=couch_conf['passwd'],
                allow_nonstandard_methods=True
                )
            raise gen.Return(resp.body)
        except HTTPError:
            # HTTP 412: Precondition Failed
            raise ValueError('Database: {0} Exist'.format(database))

    @staticmethod
    def _get_design(root):
        design_path = os.path.join(root, 'design')
        return [os.path.join(design_path, f) for f in os.listdir(design_path)]

    @gen.coroutine
    def init(self, database):
        """
        add design document to a new database
        """
        root = os.path.join(os.path.dirname(__file__), '..')
        designs = self._get_design(root)
        for design in designs:
            design_name = os.path.basename(design).split('.')[0]
            with open(design) as f:
                doc = json_decode(f.read())
                yield self.client.fetch(
                    '{0}/_design/{1}'.format(database, design_name),
                    method="PUT",
                    body=doc,
                    auth_username=couch_conf['user'],
                    auth_password=couch_conf['passwd']
                )

    @gen.coroutine
    def delete(self, database):
        try:
            resp = yield self.client.fetch(
                database,
                method="DELETE",
                auth_username=couch_conf['user'],
                auth_password=couch_conf['passwd']
            )
            raise gen.Return(resp.body)
        except HTTPError:
            raise ValueError('Database: {0} not Exist'.format(database))

    @gen.coroutine
    def list_db(self):
        resp = yield self.client.fetch('_all_dbs', method="GET", allow_nonstandard_methods=True)
        databases = [db for db in json_decode(resp.body) if not db.startswith('_')]
        raise gen.Return(databases)