Setup and configure DB

def setup_db(self, couch, dbname):
        """Setup and configure DB
        """

        # Avoid race condition of two creating db
        my_db = None

        self.log.debug('Setting up DB: %s' % dbname)

        if dbname not in couch:
            self.log.info("DB doesn't exist so creating DB: %s", dbname)
            try:
                my_db = couch.create(dbname)
            except:
                self.log.critical("Race condition caught")
                raise RuntimeError("Race condition caught when creating DB")

            try:
                auth_doc = {}
                auth_doc['_id'] = '_design/auth'
                auth_doc['language'] = 'javascript'

                auth_doc['validate_doc_update'] = """
                function(newDoc, oldDoc, userCtx) {
                if (userCtx.roles.indexOf('_admin') !== -1) {
                return;
                } else {
                throw({forbidden: 'Only admins may edit the database'});
                }
                }
                """

                my_db.save(auth_doc)
            except:
                self.log.error('Could not set permissions of %s' % dbname)

        else:
            my_db = couch[dbname]

        return my_db