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


Python rethinkdb.connect函数代码示例

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


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

示例1: __init__

    def __init__(self, server=None, port=None):

        self.server = "localhost"
        self.port = 28015
        self.r = None

        try:
            import rethinkdb as r
        except ImportError:
            from sys import exit
            print "The rethinkdb client driver is required for this object"
            exit()

        if server:
            self.server = server

        if port:
            self.port = port

        try:
            # Top level objects
            r.connect(self.server, self.port).repl()
            self.r = r

        except r.errors.RqlDriverError:
            from sys import exit
            print "WARNING.  Could not connect to %s port %s" % (self.server, self.port)
            exit()
开发者ID:gtback,项目名称:hrc-employment-diversity-report,代码行数:28,代码来源:classes.py

示例2: main

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-r", "--rethinkdb-host", default="localhost:28015")
    parser.add_argument("-m", "--machine-id", default=socket.gethostname())
    args = parser.parse_args()
    host, port = args.rethinkdb_host.split(":")

    r.connect(host, port).repl()
    try:
        r.db("logcentral")
    except r.ReqlOpFailedError:
        r.db_create("logcentral").run()

    db = r.db("logcentral")

    if 'cursor_state' not in db.table_list().run():
        r.db("logcentral").table_create("cursor_state").run()

    if 'log' not in db.table_list().run():
        r.db("logcentral").table_create("log").run()

    cursor_table = r.db("logcentral").table('cursor_state')
    log_table = r.db("logcentral").table('log')

    c = cursor_table.get(args.machine_id).run()
    c = None if c is None else c['cursor']

    for line in yield_log_lines(c):
        cursor, data = prepare_for_table(line, args.machine_id)
        log_table.insert(data).run()
        cursor_table.insert({"id": args.machine_id, "cursor": cursor}, durability="soft", conflict="replace").run()
开发者ID:teh,项目名称:logcentral,代码行数:31,代码来源:logshipper-daemon.py

示例3: connect_db

def connect_db():
    """connecting to rethinkDB"""
    r.connect('localhost', 28015).repl()
    connection = r.connect(host='localhost',
                           port=28015,
                           db='fbscrap')
    return connection
开发者ID:mnzr,项目名称:json-scraper,代码行数:7,代码来源:main.py

示例4: setup_rethinkdb

def setup_rethinkdb():
    import rethinkdb as r
    r.connect( "localhost", 28015).repl()
    try:
        r.db_create("nonpublic").run()
    except:
        pass
    try:
        r.db_create("public").run()
    except:
        pass
    db = r.db("public")
    dbs_and_tables = {'nonpublic': ['third_party_creds', 'subscribers', 'users', 'sessions'], 'public': ['crawling_instructions', 'apps', 'police_internal_affairs_cases', 'police_internal_affairs_allegations', 'organizations', 'tables', 'queries']}
    
    for database in dbs_and_tables.keys():
        try:
            r.db_create(database).run()
        except:
            pass
        db = r.db(database)
        tables_needed = dbs_and_tables[database]
        existing_tables = db.table_list().run()
        tables_to_create = set(tables_needed) - set(existing_tables) # remove existing tables from what we need
        for table in tables_to_create:
            db.table_create(table).run()
    for table in dbs_and_tables['public']:
        #tables_ids = [item['id'] for item in r.db('public').table('tables').run()]
        #if not table in tables_ids:
        if 'police' in table:
            category = "policing"
        else:
            category = "People's NSA"
        r.db('public').table('tables').insert({'id': table, 'name': table.replace('_', ' ').capitalize(), 'categories': [category]}, conflict='update').run()
开发者ID:peoplesnsallc,项目名称:peoples_nsa_api,代码行数:33,代码来源:update.py

示例5: __init__

 def __init__(self):
     r.connect('builder', 28015).repl()
     self.db = r.db('leevalley')
     #if 'sessions' not in self.db.tableList().run():
     #    self.sessions_table = self.db.table_create('sessions').run()
     #else:
     self.sessions_table = self.db.table('sessions')
开发者ID:evolvedlight,项目名称:leevalley,代码行数:7,代码来源:main.py

示例6: test_setup_db

    def test_setup_db(self):
        """ Test creation of a db and tables """
        # test that the 'TEST' database doesn't exist
        with rethinkdb.connect(host='localhost', port=28015) as conn:
            db_list = rethinkdb.db_list().run(conn)
            self.assertTrue('TEST' not in db_list)

        creations = self.run_setup_db()

        # confirm the correct tables were created
        self.assertSetEqual(creations,
            set(template.test_dataset.keys()+template.test_tables))

        with rethinkdb.connect(host='localhost', port=28015) as conn:
            # test that the 'TEST' database was created
            db_list = rethinkdb.db_list().run(conn)
            self.assertTrue('TEST' in db_list)
            conn.use('TEST')

            # test that the 'test' table was created
            table_list = rethinkdb.table_list().run(conn)
            self.assertEqual(len(table_list),
                len(template.test_dataset.keys()+template.test_tables))
            self.assertTrue(template.test_dataset.keys()[0] in table_list)

            # test that the data is correct by checking columns
            data = [row for row in rethinkdb.table(
                template.test_dataset.keys()[0]).run(conn)]
            with open(template.test_json) as f:
              self.assertSetEqual(
                  set(data[0].keys())-set([u'id']),
                  set(json.loads(f.read())[0].keys()))

        self.run_clear_test_db()
开发者ID:DAPMElab,项目名称:TBWA_Vendor_Portal,代码行数:34,代码来源:test_reader.py

示例7: main

def main():
    import rethinkdb as r
    from rethinkdb.errors import RqlRuntimeError

    # Lib para auxilio na insercao de dados de teste
    from faker import Factory
    fake = Factory.create('pt_BR')

    # Conecta ao banco local
    r.connect(HOST, PORT).repl()

    try:
        r.db_drop(DBNAME).run()
    except RqlRuntimeError:
        pass

    # Cria o banco de dados
    r.db_create(DBNAME).run()

    # Cria a tabela
    r.db(DBNAME).table_create(TABLENAME).run()

    # Insere os registros na tabela
    for frase in range(TOTAL_FRASES):
        reg = {
            'id': frase,
            'frase': fake.text(),
            'autor': fake.name()
        }
        r.db(DBNAME).table(TABLENAME).insert(reg).run()
开发者ID:gilsondev,项目名称:falcon-tutorial,代码行数:30,代码来源:restapidb.py

示例8: index

def index():

    import rethinkdb as r
    r.connect('localhost', 28015).repl()

    try:
        r.db_create('wlps').run()
    except RqlRuntimeError:
        pass

    try:
        r.db('wlps').table_create('episode').run()
    except RqlRuntimeError:
        pass

    try:
        r.db('wlps').table_create('show').run()
    except RqlRuntimeError:
        pass

    try:
        r.db('wlps').table_create('notifications').run()
    except RqlRuntimeError:
        pass

    try:
        r.db('wlps').table_create('queue').run()
    except RqlRuntimeError:
        pass
开发者ID:peppelorum,项目名称:WeLovePublicService-VHS,代码行数:29,代码来源:createdb.py

示例9: load_data_dirs

def load_data_dirs(user, dirs, state_id):
    try:
        r.connect('localhost', 30815, db='materialscommons').repl()
        for directory in dirs:
            load_directory(user, directory, state_id)
    except Exception as exc:
        raise load_data_dirs.retry(exc=exc)
开发者ID:materials-commons,项目名称:materialscommons.org,代码行数:7,代码来源:db.py

示例10: test_start

 def test_start(self):
     assert not dbc.alive()
     dbc.start()
     try:
         r.connect()
     except r.errors.ReqlDriverError:
         assert False
开发者ID:starcraftman,项目名称:new-awesome,代码行数:7,代码来源:test_util_db_control.py

示例11: 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

示例12: parse_message

    def parse_message(self, message):
        message = json.loads(message['data'])
        rethinkdb.connect('localhost', 28015).repl()
        log_db = rethinkdb.db('siri').table('logs')

        data = {
            'channel': message['channel'],
            'timestamp': rethinkdb.now(),
            'user': message['user'],
            'content': message['content'],
            'server': message['server'],
            'bot': message['bot']
        }

        log_db.insert(data).run()

        urls = re.findall(url_re, message['content'])
        if urls:
            for url in urls:
                urldata = {
                    'url': url,
                    'user': message['user'],
                    'channel': message['channel'],
                    'server': message['server'],
                    'bot': message['bot'],
                    'timestamp': rethinkdb.now()
                }
                gevent.spawn(self.parse_url, urldata)

        data['timestamp'] = datetime.datetime.utcnow()
        self.red.publish('irc_chat', json.dumps(data, default=json_datetime))
开发者ID:Ell,项目名称:Siri,代码行数:31,代码来源:listener.py

示例13: parse_url

    def parse_url(self, urldata):
        print 'GOT URL: %s' % urldata
        allowed_types = ['text', 'audio', 'image']
        video_hosts = ['www.youtube.com', 'youtube.com', 'vimeo.com', 'www.vimeo.com', 'youtu.be']
        
        r = requests.get(urldata['url'], timeout=5)
        if r.status_code == 200:
            content_type = r.headers['content-type'].split('/')[0]
            
            if content_type not in allowed_types:
                return None
            
            if content_type == 'text':
                parse = urlparse.urlparse(urldata['url'])
                if parse.hostname in video_hosts:
                    urldata['type'] = 'video'
                else:
                    urldata['type'] = 'website'

                try:
                    urldata['title'] = lxml.html.parse(urldata['url']).find(".//title").text
                except:
                    urldata['title'] = "No Title"
                
            else:
                urldata['title'] = content_type.title()
                urldata['type'] = content_type

            rethinkdb.connect('localhost', 28015).repl()
            url_db = rethinkdb.db('siri').table('urls')
            url_db.insert(urldata).run()

            urldata['timestamp'] = datetime.datetime.utcnow()
            self.red.publish('irc_urls', json.dumps(urldata, default=json_datetime))
开发者ID:Ell,项目名称:Siri,代码行数:34,代码来源:listener.py

示例14: 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

示例15: conn_rethinkdb

def conn_rethinkdb(host, port, auth_key):
    """connect to rethinkdb"""
    try:
        r.connect(host, port, auth_key=auth_key).repl()
    except ReqlDriverError as error:
        print "Error connecting to RethinkDB:", error
        exit(1)
开发者ID:btorch,项目名称:stalker,代码行数:7,代码来源:dbsetup.py


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