本文整理汇总了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()
示例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)
示例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)
示例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']
示例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)
示例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)
示例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'])
示例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']
示例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)
示例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)
示例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
示例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
示例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)
示例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
示例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)