当前位置: 首页>>代码示例>>Python>>正文


Python Server.create方法代码示例

本文整理汇总了Python中couchdb.Server.create方法的典型用法代码示例。如果您正苦于以下问题:Python Server.create方法的具体用法?Python Server.create怎么用?Python Server.create使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在couchdb.Server的用法示例。


在下文中一共展示了Server.create方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

# 需要导入模块: from couchdb import Server [as 别名]
# 或者: from couchdb.Server import create [as 别名]
def main(global_config, **settings):
    config = Configurator(settings=settings)
    config.set_authentication_policy(AuthenticationPolicy(None))
    config.set_authorization_policy(AuthorizationPolicy())
    config.add_renderer('prettyjson', JSON(indent=4))
    config.add_renderer('jsonp', JSONP(param_name='opt_jsonp'))
    config.add_renderer('prettyjsonp', JSONP(indent=4, param_name='opt_jsonp'))
    config.add_subscriber(set_renderer, NewRequest)
    config.include("cornice")
    config.route_prefix = '/api/{}'.format(VERSION)
    config.scan("openprocurement.api.views")

    # CouchDB connection
    server = Server(settings.get('couchdb.url'))
    config.registry.couchdb_server = server
    db_name = os.environ.get('DB_NAME', settings['couchdb.db_name'])
    if db_name not in server:
        server.create(db_name)
    config.registry.db = server[db_name]

    # sync couchdb views
    sync_design(config.registry.db)

    # migrate data
    migrate_data(config.registry.db)

    # S3 connection
    if 'aws.access_key' in settings and 'aws.secret_key' in settings and 'aws.bucket' in settings:
        connection = S3Connection(settings['aws.access_key'], settings['aws.secret_key'])
        config.registry.s3_connection = connection
        bucket_name = settings['aws.bucket']
        if bucket_name not in [b.name for b in connection.get_all_buckets()]:
            connection.create_bucket(bucket_name, location=Location.EU)
        config.registry.bucket_name = bucket_name
    return config.make_wsgi_app()
开发者ID:gitter-badger,项目名称:openprocurement.api,代码行数:37,代码来源:__init__.py

示例2: init_db

# 需要导入模块: from couchdb import Server [as 别名]
# 或者: from couchdb.Server import create [as 别名]
def init_db():
    server = CouchDBServer(db_addr)
    try:
        server.create(db_name)
    except PreconditionFailed:
        del server[db_name]
        server.create(db_name)
开发者ID:Tefx,项目名称:MoWSC,代码行数:9,代码来源:exp.py

示例3: create_test_users_db

# 需要导入模块: from couchdb import Server [as 别名]
# 或者: from couchdb.Server import create [as 别名]
def create_test_users_db(name=TEST_USERS_DB, server=TEST_SERVER):
    try:
        couchdb = Server(server)
        return couchdb.create(name)
    except PreconditionFailed:        
        del couchdb[name]
        return couchdb.create(name)
开发者ID:jab,项目名称:radarpost,代码行数:9,代码来源:helpers.py

示例4: initialize

# 需要导入模块: from couchdb import Server [as 别名]
# 或者: from couchdb.Server import create [as 别名]
 def initialize(self):
     couch = Server()
     if "stories" not in couch:
         couch.create("stories")
     self.db_stories = couch['stories']
     if "posts" not in couch:
         couch.create("posts")
     self.db_posts = couch['posts']
开发者ID:OpenFilter,项目名称:MediaManagerService,代码行数:10,代码来源:StoryFeedHandler.py

示例5: couchdb_connection

# 需要导入模块: from couchdb import Server [as 别名]
# 或者: from couchdb.Server import create [as 别名]
def couchdb_connection(config):

    LOGGER = getLogger("BILLING")
    LOGGER.info("Start database initialization")

    # CouchDB connection
    db_name = config.get('db').get('name')
    db_host = config.get('db').get('host')
    db_port = config.get('db').get('port')
    admin_name = config.get('admin').get('username')
    admin_pass = config.get('admin').get('password')
    aserver = Server(
        create_db_url(db_host, db_port, admin_name, admin_pass),
        session=Session(retry_delays=range(10)))
    users_db = aserver['_users']

    username = config.get('user').get('username')
    password = config.get('user').get('password')

    user_doc = users_db.get(
        'org.couchdb.user:{}'.format(username),
        {'_id': 'org.couchdb.user:{}'.format(username)}
    )

    if not user_doc.get('derived_key', '') or PBKDF2(password, user_doc.get('salt', ''), user_doc.get('iterations', 10)).hexread(int(len(user_doc.get('derived_key', '')) / 2)) != user_doc.get('derived_key', ''):
        user_doc.update({
            "name": username,
            "roles": [],
            "type": "user",
            "password": password
        })
        LOGGER.info(
            "Updating api db main user",
            extra={'MESSAGE_ID': 'update_api_main_user'}
        )
        users_db.save(user_doc)
    if db_name not in aserver:
        aserver.create(db_name)
    db = aserver[db_name]

    SECURITY[u'members'][u'names'] = [username, ]
    if SECURITY != db.security:
        LOGGER.info(
            "Updating api db security",
            extra={'MESSAGE_ID': 'update_api_security'}
        )
        db.security = SECURITY

    auth_doc = db.get(VALIDATE_DOC_ID, {'_id': VALIDATE_DOC_ID})
    if auth_doc.get('validate_doc_update') != VALIDATE_DOC_UPDATE % username:
        auth_doc['validate_doc_update'] = VALIDATE_DOC_UPDATE % username
        LOGGER.info(
            "Updating api db validate doc",
            extra={'MESSAGE_ID': 'update_api_validate_doc'}
        )
        db.save(auth_doc)
开发者ID:openprocurement,项目名称:reports,代码行数:58,代码来源:init.py

示例6: create_test_users_db

# 需要导入模块: from couchdb import Server [as 别名]
# 或者: from couchdb.Server import create [as 别名]
def create_test_users_db(config=None):
    if config is None: 
        config = load_test_config()
    name = config['couchdb.users_database']
    try:
        couchdb = Server(config['couchdb.address'])
        return couchdb.create(name)
    except PreconditionFailed:        
        del couchdb[name]
        return couchdb.create(name)
开发者ID:ltucker,项目名称:radarpost,代码行数:12,代码来源:helpers.py

示例7: handle

# 需要导入模块: from couchdb import Server [as 别名]
# 或者: from couchdb.Server import create [as 别名]
    def handle(self, *args, **options):

        verbosity = options['verbosity']
        if verbosity == '0':
            self.logger.setLevel(logging.ERROR)
        elif verbosity == '1':
            self.logger.setLevel(logging.WARNING)
        elif verbosity == '2':
            self.logger.setLevel(logging.INFO)
        elif verbosity == '3':
            self.logger.setLevel(logging.DEBUG)

        self.offset = int(options['offset'])
        self.limit = int(options['limit'])

        self.logger.info("Starting export!")
        server = Server()
        if 'maps-places' not in server:
            self.db = server.create('maps-places')
        else:
            self.db = server['maps-places']

        # places uri startup
        places_uri = "{0}/maps/places".format(settings.OP_API_URI)
        self.logger.debug("GET {0}".format(places_uri))

        # get all places, following the next link
        places_json = self.export_page(places_uri)
        while places_json and places_json['next']:
            places_json = self.export_page(places_json['next'])
开发者ID:openpolis,项目名称:op_api3,代码行数:32,代码来源:maps_export_to_couchdb.py

示例8: PostTestCase

# 需要导入模块: from couchdb import Server [as 别名]
# 或者: from couchdb.Server import create [as 别名]
class PostTestCase(unittest.TestCase):
	def setUp(self):
		self.server = Server(settings.COUCHDB_SERVER)
		try:
			self.db = self.server.create('comfy_blog_test')
		except:
			self.db = self.server['comfy_blog_test']
		
		self.post1 = Post(title=u"Hello, World!", slug=u"foo-bar", published=datetime(2008, 8, 8), author={'name': 'Myles Braithwaite', 'email': '[email protected]'})
		self.post2 = Post(title=u"Hello, World!", published=datetime(2007, 7, 7))
		self.post1.store()
		self.post2.store()
	
	def testURL(self):
		self.assertEquals(self.post1.get_absolute_url(), '/blog/2008/8/8/foo-bar/')
		self.assertEquals(self.post2.get_absolute_url(), '/blog/2007/7/7/hello-world/')
	
	def testSlugify(self):
		self.assertEquals(self.post2.slug, 'hello-world')
	
	#def testAddComment(self):
	#	post = Post.load(self.db, self.post1.id)
	#	coment = post.comments()
	#	comment.author = {'name': u"Myles Braithwaite", 'email': "[email protected]", 'url': u"http://mylesbraithwaite.com/"}
	#	comment.comment = u"Hello, World!"
	#	comment.time = datetime.now()
	#	comment.user_agent = u"Python Unit Test"
	#	comment.ip_address = u"127.0.0.1"
	#	comment.is_spam = False
	#	post.store()
	#	# TODO Still working on doing something here to see if the test actually worked.
	
	def tearDown(self):
		del self.server['comfy_blog_test']
开发者ID:myles-archive,项目名称:comfy,代码行数:36,代码来源:tests.py

示例9: main

# 需要导入模块: from couchdb import Server [as 别名]
# 或者: from couchdb.Server import create [as 别名]
def main(bulk_size, up_to, num_threads):
    global timer
    s = Server('http://localhost:5984')
    if 'test' in s:
        del s['test']
    db = s.create('test')

    stats_file = 'bulk-perf-%s-%s-%s.dat' % (bulk_size, up_to, num_threads)
    title_file = stats_file + '.meta'
    f = open(title_file, 'w')
    f.write('Bulk size: %s, num threads: %s' % (bulk_size, num_threads))
    f.close()

    stats_file = open(stats_file, 'w')

    stats_lock = Lock()
    exit_event = Event()

    chunks = Queue.Queue()

    def process_chunks():
        global count, timer, internal_counter

        s = Server('http://localhost:5984')
        db = s['test']

        while not exit_event.isSet():
            try:
                chunk = list(chunks.get(timeout=5))
                chunks.task_done()

                db.update(chunk)

                stats_lock.acquire()
                try:
                    count += bulk_size
                    internal_counter += bulk_size

                    if internal_counter >= max(num_threads*bulk_size, up_to/1000):
                        end = time()

                        stats_file.write('%s %s\n' % (count, internal_counter/float(end-timer)))
                        stats_file.flush()

                        timer = end
                        internal_counter = 0
                        print '%.1f%%' % (float(count) / up_to * 100)
                finally:
                    stats_lock.release()

            except Queue.Empty:
                pass

            except Exception, e:
                print 'Exception: %r' % (e,)
                chunks.put(chunk)
                sleep(1)
开发者ID:svetlyak40wt,项目名称:couchdb-performance-tests,代码行数:59,代码来源:couchdb_bulk_perf.py

示例10: __init__

# 需要导入模块: from couchdb import Server [as 别名]
# 或者: from couchdb.Server import create [as 别名]
 def __init__(self):
     couchdb_host = getattr(settings, 'COUCHDB_HOST')
     server       = Server(couchdb_host)
     try:
         self.db  = server['wiki']
     except ResourceNotFound:
         self.db  = server.create('wiki')
         Page.get_pages.sync(self.db)
     self.wiki_form = curry(PageForm, db = self.db)
开发者ID:theju,项目名称:django-couch-wiki,代码行数:11,代码来源:views.py

示例11: create_db

# 需要导入模块: from couchdb import Server [as 别名]
# 或者: from couchdb.Server import create [as 别名]
def create_db(database):
    server = Server('http://localhost:5984/')
    try:
        db = server.create(database)
        logger.info('[DB] Database %s created' % database)
    except PreconditionFailed:
        db = server[database]
        logger.info('[DB] Database %s already exists.' % database)

    return db
开发者ID:poupotte,项目名称:couchdb-fuse,代码行数:12,代码来源:dbutils.py

示例12: get_couchdb

# 需要导入模块: from couchdb import Server [as 别名]
# 或者: from couchdb.Server import create [as 别名]
def get_couchdb(dbname, uri=None):
    if uri:
        server = Server(uri)
    else:
        server = Server()
    if dbname in server:
        db = server[dbname]
    else:
        db = server.create(dbname)
    return db
开发者ID:sbrauer,项目名称:cornice_couch_demo,代码行数:12,代码来源:__init__.py

示例13: __init__

# 需要导入模块: from couchdb import Server [as 别名]
# 或者: from couchdb.Server import create [as 别名]
class GeonamesLoader:
	
	total_inserts = 0
	
	def __init__(self):
		
		uri = 'http://localhost:5984/'
		self.cache_dir = tempfile.mkdtemp(prefix='couchdb')
		self.server = Server(uri, cache=self.cache_dir)

		try:
			self.db = self.server['geonames']
		except ResourceNotFound:
			self.db = self.server.create('geonames')

	def load_data(self, data_file_path, field_keys):
		
		data_file = open(data_file_path, 'r')
		docs = []
		max_docs_per_insert = 1000
		i = 0

		for line in data_file:
			values = line.decode('utf8')
			values = values.rstrip().split("\t")
			doc = dict(zip(field_keys, values))

			# remove blank values
			for k, v in doc.items():
				if len(v) == 0:
					del doc[k]

			doc['_id'] = uuid4().hex
			docs.append(doc)
			
			if i == max_docs_per_insert:
				self.bulk_insert_docs(docs)
				docs = []
				i = 0
				
			i = i+1
		
		self.bulk_insert_docs(docs)
		data_file.close()
		
	def bulk_insert_docs(self, docs):
		num_docs = len(docs)
		if num_docs != 0:
			self.db.update(docs)
			print "inserted %d docs" % num_docs
			
			self.total_inserts = self.total_inserts + num_docs
		
	def __del__(self):
		shutil.rmtree(self.cache_dir)	
开发者ID:andyuk,项目名称:couchdb-data-importer,代码行数:57,代码来源:couchdb-loader.py

示例14: create_db

# 需要导入模块: from couchdb import Server [as 别名]
# 或者: from couchdb.Server import create [as 别名]
def create_db(name):
    '''
    Create a new name for given name.
    '''
    server = Server('http://localhost:5984/')
    try:
        db = server.create(name)
        logger.info('[DB] Database %s created' % name)
    except PreconditionFailed:
        db = server[name]
        logger.info('[DB] Database %s already exists.' % name)

    return db
开发者ID:frankrousseau,项目名称:cozy-fuse,代码行数:15,代码来源:dbutils.py

示例15: DatabaseBackend

# 需要导入模块: from couchdb import Server [as 别名]
# 或者: from couchdb.Server import create [as 别名]
class DatabaseBackend(object):

    def __init__(self, server=SERVER_HOST, database_name = DATABASE_NAME, *args, **kwargs):
        self.url = server
        self.server = Server(self.url)
        try:
            self.database = self.server[database_name]
        except ResourceNotFound:
            self.database = self.server.create(database_name)

    def save(self, document, obj):
        document.store(self.database)
        return obj
    
    def get_data_records_type(self, entity):
        endkey = [entity.uuid, int(mktime(datetime.datetime.now().timetuple())) * 1000]
        return self.filter_rows_by_uuid(entity.uuid,'data_types', endkey = endkey)

    def get_data_records_aggregated(self, entity, data_records_func, asof):
        aggregated_result = {}
        endkey = [entity.uuid, int(mktime(asof.timetuple())) * 1000]
        for name, aggregation_type in data_records_func.items():
            data = self.filter_rows_by_uuid(entity.uuid, aggregation_type, endkey)
            aggregated_result[name] = data[name] if name in data.keys() else None
            
        return aggregated_result

    def filter_rows_by_uuid(self, uuid, aggregation_type, endkey = None):
        view_url = '_design/' + DESIGN_DOCUMENT_NAME + '/_view/' + VIEWS[aggregation_type]
        rows = self.database.view(view_url, group=True, group_level = 1, endkey = endkey).rows
        value = None
        for row in rows:
            if row.key[0] == uuid:
                value = row.value
                break
        
        return value
        

    def get(self, uuid, document):
        return document.load(self.database, uuid)
        
    def __unicode__(self):
        return u"Connected on %s - working on %s" % (self.url, self.database_name)

    def __str__(self):
        return unicode(self)

    def __repr__(self):
        return repr(self.database)
开发者ID:diptanu,项目名称:datastore,代码行数:52,代码来源:backend.py


注:本文中的couchdb.Server.create方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。