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


Python rethinkdb.db函数代码示例

本文整理汇总了Python中rethinkdb.db函数的典型用法代码示例。如果您正苦于以下问题:Python db函数的具体用法?Python db怎么用?Python db使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: put

    async def put(self):
        """
        .. http:put:: /?queue={string:queue}

            Creates a queue if it does not exist.

        **Example request**:

        .. sourcecode:: http

            GET /?queue=foo
            Host: example.com
            Accept: application/json, text/javascript

        **Example response**:

        .. sourcecode:: http

            HTTP/1.1 200 OK
            Vary: Accept
            Content-Type: text/javascript

            ok

        :query queue: queue (table) to create
        :statuscode 200: This method always should return 200

        """
        opts = self.request.app['rethinkdb']
        conn = await r.connect(**opts)
        qname = self.request.GET['queue']
        with suppress(r.errors.ReqlOpFailedError):
            r.db(opts['db']).table_create(qname).run(conn)

        return web.Response(body=b'ok')
开发者ID:XayOn,项目名称:tqueues,代码行数:35,代码来源:dispatcher.py

示例2: LoadTestData

def LoadTestData(file, db, conn, v = False):
  '''Loading test data into the database.'''

  ## Loading data.
  data_dir = os.path.split(dir)[0]
  path = os.path.join(data_dir, 'tests', 'data', file)
  print path
  try:
    with open(path) as csv_file:
      data = csv.DictReader(csv_file)
      test_data = []
      for row in data:
        test_data.append(row)

  except Exception as e:
    print "Couldn't load test data."
    return False


  ## Storing in db.
  try:
    # Checking for existing records.
    n = r.db(db['name']).table('values').count().run(conn)
    if n > 0:
      if v:
        print "Data already in db. Deleting ..."
      r.db(db['name']).table('values').delete().run(conn)

    r.db(db['name']).table('values').insert(test_data).run(conn)
    return True

  except Exception as e:
    print "Could not insert data into database."
    return False
开发者ID:luiscape,项目名称:hio-setup,代码行数:34,代码来源:setup_db.py

示例3: get_tables

def get_tables(host, port, auth_key, tables):
    try:
        conn = r.connect(host, port, auth_key=auth_key)
    except r.RqlDriverError as ex:
        raise RuntimeError(ex.message)

    dbs = r.db_list().run(conn)
    res = []

    if len(tables) == 0:
        tables = [[db] for db in dbs]

    for db_table in tables:
        if db_table[0] not in dbs:
            raise RuntimeError("Error: Database '%s' not found" % db_table[0])

        if len(db_table) == 1: # This is just a db name
            res.extend([(db_table[0], table) for table in r.db(db_table[0]).table_list().run(conn)])
        else: # This is db and table name
            if db_table[1] not in r.db(db_table[0]).table_list().run(conn):
                raise RuntimeError("Error: Table not found: '%s.%s'" % tuple(db_table))
            res.append(tuple(db_table))

    # Remove duplicates by making results a set
    return set(res)
开发者ID:JorgeRios,项目名称:blogember,代码行数:25,代码来源:_export.py

示例4: init_database_with_default_tables

def init_database_with_default_tables(args):
    """
    Create a new RethinkDB database and initialise (default) tables

    :param args: an argparse argument (force)
    """
    # Add additional (default) tables here...
    def_tables = ['determined_variants', 'strains_under_investigation',
                  'references', 'reference_features', 'strain_features']
    with database.make_connection() as connection:
        try:
            r.db_create(connection.db).run(connection)
            for atable in def_tables:
                r.db(connection.db).table_create(atable).run(connection)
        except RqlRuntimeError:
            print ("Database %s already exists. Use '--force' option to "
                   "reinitialise the database." % (connection.db))
            if args.force:
                print "Reinitialising %s" % (connection.db)
                r.db_drop(connection.db).run(connection)
                r.db_create(connection.db).run(connection)
                for atable in def_tables:
                    r.db(connection.db).table_create(atable).run(connection)
            else:
                sys.exit(1)
        print ("Initalised database %s. %s contains the following tables: "
               "%s" % (connection.db, connection.db, ', '.join(def_tables)))
开发者ID:m-emerson,项目名称:BanzaiDB,代码行数:27,代码来源:banzaidb.py

示例5: create

    def create(self):
        conn = self.connect()

        db_list = r.db_list().run(conn)

        db_created = False
        table_created = False

        if not self.db_name in db_list:
            r.db_create(self.db_name).run(conn)
            db_created = True

        table_list = r.db(self.db_name).table_list().run(conn)

        if not self.config_table_name in table_list:
            r.db(self.db_name).table_create(
                self.config_table_name, primary_key=self.primary_key
            ).run(conn)

            r.db(self.db_name).table(self.config_table_name)\
                .index_create(self.secondary_index).run(conn)

            table_created = True

        return {"db": db_created, "table": table_created}
开发者ID:IAmUser4574,项目名称:zeromq-ros,代码行数:25,代码来源:db.py

示例6: upload_project

def upload_project(project_id):
    """
    Upload the bup backup of this project to the gcloud bucket.
    """
    path = path_to_project(project_id)

    run("sudo chmod a+r -R %s"%path)

    log('path: ', project_id)
    bup = os.path.join(path, 'bup')
    if not os.path.exists(bup):
        raise RuntimeError("no bup directory to upload -- done")
    target = os.path.join('gs://{bucket}/projects/{project_id}.zfs/bup'.format(
            bucket=GCLOUD_BUCKET, project_id=project_id))

    log('upload: rsync new pack files')
    run(['gsutil', '-m', 'rsync', '-x', '.*\.bloom|.*\.midx', '-r',
         '{bup}/objects/'.format(bup=bup),
         '{target}/objects/'.format(target=target)])
    log('gsutil upload refs/logs')
    for path in ['refs', 'logs']:
        run(['gsutil', '-m', 'rsync', '-c', '-r',
             '{bup}/{path}/'.format(bup=bup, path=path),
             '{target}/{path}/'.format(target=target, path=path)])

    #auth_key = open(RETHINKDB_SECRET).read().strip()
    conn = rethinkdb.connect(host=DB_HOST, timeout=10)#, auth_key=auth_key)
    timestamp = datetime.datetime.fromtimestamp(time.time()).strftime(TIMESTAMP_FORMAT)
    rethinkdb.db('smc').table('projects').get(project_id).update(
        {'last_backup_to_gcloud':timestamp_to_rethinkdb(timestamp)}).run(conn)
开发者ID:DrXyzzy,项目名称:smc,代码行数:30,代码来源:upload_project.py

示例7: get_table

	def get_table():
		try:
			r.db(dbname).table_create('boards').run(_get_conn())
		except r.RqlRuntimeError:
			# already created
			pass
		return r.db(dbname).table('boards')
开发者ID:jskrzypek,项目名称:leaderboard,代码行数:7,代码来源:models.py

示例8: step1

def step1():

    response = {}
    conn = r.connect(host=current_app.config['RETHINKDB_HOST'])

    users = json.loads(request.data)
    users = {
        'name': users['name'],
        'user': users['user'],
        'email': users['email'],
        'password': users['password'],
        'ubication': [],
        'sale': []
    }
    
    check_user = r.db('food').table('user_register').filter({'email': users['email']}).run(conn)
    check_user = list(check_user)
    if len(check_user) > 0:
        
        response['success'] = 200
        response['message'] = u'El usuario ya existe'
        response['code'] = 1

    else:    
     
        insert = r.db(current_app.config['DATABASE']).table('user_register').insert(users).run(conn)
        response['success'] = 200
        response['message'] = u'Usuario registrado'
        response['code'] = 0

    pprint.pprint(response)
    return jsonify(response)
开发者ID:omarlopez,项目名称:appRestaurant,代码行数:32,代码来源:views.py

示例9: main

def main():
    # connect rethinkdb
    rethinkdb.connect("localhost", 28015, "mysql")
    try:
        rethinkdb.db_drop("mysql").run()
    except:
        pass
    rethinkdb.db_create("mysql").run()

    tables = ["dept_emp", "dept_manager", "titles",
              "salaries", "employees", "departments"]
    for table in tables:
        rethinkdb.db("mysql").table_create(table).run()

    stream = BinLogStreamReader(
        connection_settings=MYSQL_SETTINGS,
        blocking=True,
        only_events=[DeleteRowsEvent, WriteRowsEvent, UpdateRowsEvent],
    )

    # process Feed
    for binlogevent in stream:
        if not isinstance(binlogevent, WriteRowsEvent):
            continue

        for row in binlogevent.rows:
            if not binlogevent.schema == "employees":
                continue

            vals = {}
            vals = {str(k): str(v) for k, v in row["values"].iteritems()}
            rethinkdb.table(binlogevent.table).insert(vals).run()

    stream.close()
开发者ID:Affirm,项目名称:python-mysql-replication,代码行数:34,代码来源:rethinkdb_sync.py

示例10: go

def go():
    with except_printer():
        r.connect(host="localhost", port="123abc")
    with except_printer():
        r.expr({'err': r.error('bob')}).run(c)
    with except_printer():
        r.expr([1,2,3, r.error('bob')]).run(c)
    with except_printer():
        (((r.expr(1) + 1) - 8) * r.error('bob')).run(c)
    with except_printer():
        r.expr([1,2,3]).append(r.error('bob')).run(c)
    with except_printer():
        r.expr([1,2,3, r.error('bob')])[1:].run(c)
    with except_printer():
        r.expr({'a':r.error('bob')})['a'].run(c)
    with except_printer():
        r.db('test').table('test').filter(lambda a: a.contains(r.error('bob'))).run(c)
    with except_printer():
        r.expr(1).do(lambda x: r.error('bob')).run(c)
    with except_printer():
        r.expr(1).do(lambda x: x + r.error('bob')).run(c)
    with except_printer():
        r.branch(r.db('test').table('test').get(0)['a'].contains(r.error('bob')), r.expr(1), r.expr(2)).run(c)
    with except_printer():
        r.expr([1,2]).reduce(lambda a,b: a + r.error("bob")).run(c)
开发者ID:isidorn,项目名称:test2,代码行数:25,代码来源:test.py

示例11: setDictionary

def setDictionary():
	dict = {}
	#print "getting top stories from hacker-news"
	result = firebase.get('/v0/topstories', None)
	# result = result[:200]
	for itemid in result:
		try:
			data = firebase.get('/v0/item/' + str(itemid), None)
			if (data['type'] == 'story'):
				# get tags
				url = data['url']
				(to_insert, tags) = selectTags(itemid)
				# store to temp db
				r.db("tagger_db").table("id2html").insert({"id": itemid, "tag_string": to_insert}).run(connection)
				if len(tags) > 1:
					title = data['title']
					score = str(data['score'])
					usr = data['by']
					comments = str(data['descendants'])
					myString = "<tr class='athing'><td align=\"right\" valign=\"top\" class=\"title\"><span class=\"rank\"> </span></td><td><center><a id=\"up_10287983\"><div class=\"votearrow\" title=\"upvote\"></div></a></center></td><td class=\"title\"><span class=\"deadmark\"></span><a href=\"" + url + "\">" + title + "</a>" + to_insert + "</td><td><center><a id=\"up_10287983\"><div class=\"votearrow\" title=\"upvote\"></div></a></center></td></tr><tr><td colspan=\"2\"></td><td class=\"subtext\"><span class=\"score\">" + score + " points</span> by <a>" + usr + "</a> | <a>" + comments +" comments</a></td></tr><tr class=\"spacer\" style=\"height:5px\"></tr>"
					print "tags: ", tags[0], tags[1]
					add(tags[0], myString, dict)
					add(tags[1], myString, dict)
		except KeyError:
			pass
	# r.db("test").table("tag_dict").delete().run(connection)
	r.db("tagger_db").table("tag2html").insert(dict).run(connection)
开发者ID:zljiljana,项目名称:TaggerNews,代码行数:27,代码来源:parser.py

示例12: __init__

 def __init__(self, count):
     self.con = r.connect("localhost", 28015).repl()
     tables = r.db("test").table_list().run(self.con)
     if "items" in tables:
         r.db("test").table_drop("items").run(self.con)
     r.db("test").table_create("items").run(self.con)
     self.count = count
开发者ID:karlgrz,项目名称:nosql-comparison,代码行数:7,代码来源:rethinkdbtest.py

示例13: sync_facebook

def sync_facebook(name):
    #import ipdb; ipdb.set_trace();
    try:
        form_data = json.loads(request.data)
    except:
        return response_msg('error', 'data not correct')

    try:
        graph = GraphAPI(form_data['access_token'])
        try:
            # #import ipdb; ipdb.set_trace();
            email = graph.get_object('me', fields='email')['email']
            pic = graph.get_object('me/picture', width='400', height='400')['url']
            print pic
            if email != form_data['fb_email']:
                return response_msg('error', 'incorrect facebook email')
        except:
            return response_msg('error', 'data not complete')
    except:
        return response_msg('error', 'invalid access token')

    try:
        connection = get_rdb_conn()
        cursor = rdb.db(TODO_DB).table('user').filter(
            rdb.row['username'] == name
            ).update({'fb_email': email, 'pic': pic}
            ).run(connection)
        cursor = rdb.db(TODO_DB).table('user').filter(
            rdb.row['username'] == name
            ).run(connection)
    except:
        return response_msg('error', 'Could not connect to db')

    return response_msg('success', 'OK', data=cursor.items[0])
开发者ID:sundarrinsa,项目名称:longclaw,代码行数:34,代码来源:views.py

示例14: sync_ratings

def sync_ratings():
    try:
        connection = get_rdb_conn()
        cursor = rdb.db(TODO_DB).table('user').run(connection)
    except:
        return response_msg('error', 'could not connect to db')
    for user in cursor.items:
        ratings = rating(user['cfhandle'], user['cchandle'], user['colg_rating'])
        ratings = json.loads(ratings[0])
        colg_rating = 0
        try:
            colg_rating = colg_rating + 20 * ((ratings['cf_rating']/100)**2)
            colg_rating = colg_rating + 2000 + 7 * (((ratings['lrating']/1000)**2) + (ratings['lrating']/20))
            colg_rating = colg_rating + 2000 + 5 * (((ratings['srating']/100)**2) + (ratings['srating']/20))
        except:
            pass
        print colg_rating
        try:
            cursor = rdb.db(TODO_DB).table('user').filter(
                rdb.row['username'] == user['username']
                ).update({
                'lrating': ratings['lrating'],
                'srating': ratings['srating'],
                'cfrating': ratings['cf_rating'],
                'colg_rating': colg_rating/3,
                }).run(connection)
            print user['username']
        except:
            print 'error' + user['username']

    return response_msg('sucess', 'OK')
开发者ID:sundarrinsa,项目名称:longclaw,代码行数:31,代码来源:views.py

示例15: remove_pending_user

 def remove_pending_user(self, user_id, row_id, user_pending_name=None):
     """
     removes a user id to a model's pending list.
     """
     if user_id is None:
         logging.error("user_id cannot be None")
         return False
     if row_id is None:
         logging.error("row_id cannot be None")
         return False
     row_table = self.__class__.__name__
     user_table = 'User'
     user_data = r.db(self.DB).table(user_table).get(user_id).run(self.conn)
     row_data = r.db(self.DB).table(row_table).get(row_id).run(self.conn)
     if user_data is None:
         logging.error("User {0} does not exist".format(user_data))
         return False
     if row_data is None:
         logging.error("{0} {1} does not exist".format(row_table, row_data))
         return False
     if user_pending_name is not None:
         user_pending = user_data.get(user_pending_name, [])
         try:
             user_pending.remove(row_id)
         except ValueError:
             logging.warn("row_id {0} not in user {1}".format(row_id, user_pending_name))
             pass
         r.db(self.DB).table(user_table).get(user_id).update({user_pending_name: user_pending}).run(self.conn)
     penders = row_data['penders']
     try:
         penders.remove(user_id)
     except ValueError:
         pass
     return r.db(self.DB).table(row_table).get(row_id).update({'penders': penders}).run(self.conn)
开发者ID:sungbae,项目名称:scq,代码行数:34,代码来源:basemodel.py


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