python类OperationalError()的实例源码

db.py 文件源码 项目:jarvis 作者: anqxyr 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def init(path):
    """Initialize the database, create missing tables."""
    db.init(path)

    try:
        migrator = playhouse.migrate.SqliteMigrator(db)
        playhouse.migrate.migrate(
            migrator.add_column(
                'ChannelConfig', 'gibber', peewee.BooleanField(null=True)))
    except peewee.OperationalError:
        pass

    db.connect()
    db.create_tables([
        Tell, Message, Quote, Memo,
        Subscriber, Restricted, Alert, ChannelConfig], safe=True)
config.py 文件源码 项目:farnsworth 作者: mechaphish 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def execute_sql(self, sql, params=None, require_commit=True):
        @retry(wait_exponential_multiplier=500,
               wait_exponential_max=10000,
               stop_max_attempt_number=10,
               retry_on_exception=self.retry_if_peewee_error)
        def execute():
            try:
                cursor = super(RetryHarderOperationalError, self) \
                    .execute_sql(sql, params, require_commit)
            except (peewee.OperationalError, peewee.InterfaceError), error:
                print LOG.debug("Retrying after Peewee error: %s", error.message)
                if not self.is_closed():
                    self.close()
                with self.exception_wrapper():
                    cursor = self.get_cursor()
                    cursor.execute(sql, params or ())
                    if require_commit and self.get_autocommit():
                        self.commit()
            return cursor
        return execute()
init.py 文件源码 项目:sentinel-old 作者: monacocoin-net 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def is_database_correctly_configured():
    import peewee
    import config

    configured = False

    cannot_connect_message = "Cannot connect to database. Please ensure database service is running and user access is properly configured in 'sentinel.conf'."

    try:
        db = config.db
        db.connect()
        configured = True
    except (peewee.ImproperlyConfigured, peewee.OperationalError, ImportError) as e:
        print("[error]: %s" % e)
        print(cannot_connect_message)
        sys.exit(1)

    return configured
models.py 文件源码 项目:sentinel-old 作者: monacocoin-net 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def check_db_sane():
    """ Ensure DB tables exist, create them if they don't. """
    check_db_schema_version()

    missing_table_models = []

    for model in db_models():
        if not getattr(model, 'table_exists')():
            missing_table_models.append(model)
            printdbg("[warning]: table for %s (%s) doesn't exist in DB." % (model, model._meta.db_table))

    if missing_table_models:
        printdbg("[warning]: Missing database tables. Auto-creating tables.")
        try:
            db.create_tables(missing_table_models, safe=True)
        except (peewee.InternalError, peewee.OperationalError, peewee.ProgrammingError) as e:
            print("[error] Could not create tables: %s" % e)

    update_schema_version()
models.py 文件源码 项目:sentinel-old 作者: monacocoin-net 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def check_db_schema_version():
    """ Ensure DB schema is correct version. Drop tables if not. """
    db_schema_version = None

    try:
        db_schema_version = Setting.get(Setting.name == 'DB_SCHEMA_VERSION').value
    except (peewee.OperationalError, peewee.DoesNotExist, peewee.ProgrammingError) as e:
        printdbg("[info]: Can't get DB_SCHEMA_VERSION...")

    printdbg("[info]: SCHEMA_VERSION (code) = [%s]" % SCHEMA_VERSION)
    printdbg("[info]: DB_SCHEMA_VERSION = [%s]" % db_schema_version)
    if (SCHEMA_VERSION != db_schema_version):
        printdbg("[info]: Schema version mis-match. Syncing tables.")
        try:
            existing_table_names = db.get_tables()
            existing_models = [m for m in db_models() if m._meta.db_table in existing_table_names]
            if (existing_models):
                printdbg("[info]: Dropping tables...")
                db.drop_tables(existing_models, safe=False, cascade=False)
        except (peewee.InternalError, peewee.OperationalError, peewee.ProgrammingError) as e:
            print("[error] Could not drop tables: %s" % e)
init.py 文件源码 项目:sentinel 作者: dashpay 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def is_database_correctly_configured():
    import peewee
    import config

    configured = False

    cannot_connect_message = "Cannot connect to database. Please ensure database service is running and user access is properly configured in 'sentinel.conf'."

    try:
        db = config.db
        db.connect()
        configured = True
    except (peewee.ImproperlyConfigured, peewee.OperationalError, ImportError) as e:
        print("[error]: %s" % e)
        print(cannot_connect_message)
        sys.exit(1)

    return configured
models.py 文件源码 项目:sentinel 作者: dashpay 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def check_db_sane():
    """ Ensure DB tables exist, create them if they don't. """
    check_db_schema_version()

    missing_table_models = []

    for model in db_models():
        if not getattr(model, 'table_exists')():
            missing_table_models.append(model)
            printdbg("[warning]: table for %s (%s) doesn't exist in DB." % (model, model._meta.db_table))

    if missing_table_models:
        printdbg("[warning]: Missing database tables. Auto-creating tables.")
        try:
            db.create_tables(missing_table_models, safe=True)
        except (peewee.InternalError, peewee.OperationalError, peewee.ProgrammingError) as e:
            print("[error] Could not create tables: %s" % e)

    update_schema_version()
    purge_invalid_amounts()
models.py 文件源码 项目:sentinel 作者: dashpay 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def check_db_schema_version():
    """ Ensure DB schema is correct version. Drop tables if not. """
    db_schema_version = None

    try:
        db_schema_version = Setting.get(Setting.name == 'DB_SCHEMA_VERSION').value
    except (peewee.OperationalError, peewee.DoesNotExist, peewee.ProgrammingError) as e:
        printdbg("[info]: Can't get DB_SCHEMA_VERSION...")

    printdbg("[info]: SCHEMA_VERSION (code) = [%s]" % SCHEMA_VERSION)
    printdbg("[info]: DB_SCHEMA_VERSION = [%s]" % db_schema_version)
    if (SCHEMA_VERSION != db_schema_version):
        printdbg("[info]: Schema version mis-match. Syncing tables.")
        try:
            existing_table_names = db.get_tables()
            existing_models = [m for m in db_models() if m._meta.db_table in existing_table_names]
            if (existing_models):
                printdbg("[info]: Dropping tables...")
                db.drop_tables(existing_models, safe=False, cascade=False)
        except (peewee.InternalError, peewee.OperationalError, peewee.ProgrammingError) as e:
            print("[error] Could not drop tables: %s" % e)
test_core.py 文件源码 项目:paper-to-git 作者: maxking 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_initialize_2(self, tmpdir_factory):
        var_dir = tmpdir_factory.mktemp('temp_var')
        test_config = var_dir.join('paper-git.cfg')
        with test_config.open(ensure=True, mode='w') as fp:
            print("""
[dropbox]
api_token: thisisanotherapikey
            """, file=fp)
        assert config.dbox is None
        assert config.db.path is None
        with pytest.raises(peewee.OperationalError):
            config.db.db.connect()
        with var_dir.as_cwd():
            initialize()
        # Make sure that the database connection works.
        assert config.db.path is not None
        assert set(config.db.db.get_tables()) == set([
            'paperdoc', 'paperfolder', 'sync'])
        assert config.dbox is not None
db_operation.py 文件源码 项目:Malicious_Domain_Whois 作者: h-j-13 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def query_whois_info(self, domain):
        try:
            domain_hash = hash(domain)
            table_num = get_table_num(domain_hash)
            query_results = self.model_list[table_num].select(
            ).where(
                self.model_list[table_num].domain_hash == domain_hash,
                self.model_list[table_num].domain == domain
            )
            return query_results
        except peewee.OperationalError as e:
            raise e
        except TableChoiceError as e:
            raise e

    # ?????????
    # @param table_num ???
    # @param tld ????
models.py 文件源码 项目:PyAlpha 作者: raj-krishnan 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def setup_portfolio_database():
    """
    Create database tables if required
    """
    try:
        TableStockExchange.create_table()
    except peewee.OperationalError:
        print("Stock Exchange table already exists!")

    try:
        TableUserPortfolio.create_table()
    except peewee.OperationalError:
        print("User Portfolio table already exists!")

    try:
        TableLogger.create_table()
    except peewee.OperationalError:
        print("Logger table already exists!")
loredb.py 文件源码 项目:loredb 作者: christhompson 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def import_lore(old_lore):
    try:
        Lore.create_table()
    except peewee.OperationalError:
        print("Lore table already exists")

    with open(old_lore, newline='') as f:
        reader = csv.reader(f, delimiter='|')
        for row in reader:
            t_str = row[0]
            author = row[1]
            lore = row[2]
            try:
                t = datetime_parser.parse(t_str)
            except ValueError:
                t = None
            Lore.create(time=t, author=author, lore=lore)
main.py 文件源码 项目:kivy_gosh 作者: mcroni 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def ping(*args):
    count = 0
    try:
        for message in Announcementss.select():
            count += 1
        print count
        if count == store.get('announcements')['count']:
            print 'yeah'
            osc.sendMsg(
                '/message',
                [''.join('yeah'), ],
                port=3002)
        else:
            kwargs = {'title': 'hey', 'message': 'New Devotion in ', 'ticker': 'New Devotion','timeout':4}
            print 'nah'
            store.put('announcements',count=count)
            notification.notify(**kwargs)
            vibrator.vibrate(.5)
    except peewee.OperationalError:
        print('cant connect')
    else:
        pass
main.py 文件源码 项目:pyTrack 作者: clamytoe 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def main():
    """Displays all projects

    If command line arguments are used, they are passed on to click to process,
    if not, then all of the projects currently being worked on are displayed.
    """
    try:
        db.connect()
    except OperationalError:
        pass

    try:
        db.create_tables([Log, Project], True)
    except OperationalError:
        pass
    else:
        if len(argv) > 1:
            cli()
        else:
            _ = get_projects(display=True)
    finally:
        db.close()
database_client.py 文件源码 项目:DuratorEmu 作者: Shgck 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
def _test_db(self):

        @db_connection
        def get_test_value():
            return 1325  # misc value, the decorator will return None on failure

        test_value = None
        try:
            test_value = get_test_value()
        except OperationalError as exc:
            print("Exception caught: " + str(exc))

        if test_value is not None:
            print("Database access test OK")
        else:
            print("Database access test failed :(")
config.py 文件源码 项目:farnsworth 作者: mechaphish 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def retry_if_peewee_error(cls, error):
        return isinstance(error, (peewee.OperationalError,
                                  peewee.InterfaceError))
db.py 文件源码 项目:pocket48-tools 作者: zyf-website 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def set_live_subscription(subscriptor, member_ids):
    """
    ?????????????????????????
    subscriptor??????????tuple?
    ??????????????????????
    """
    if not isinstance(member_ids, (list, tuple)):
        member_ids = [member_ids]
    if isinstance(subscriptor, (list, tuple)) and len(subscriptor) == 2:
        params = {
            'pocket48_phonenum': subscriptor[0],
            'pocket48_password': subscriptor[1],
        }
    elif isinstance(subscriptor, (str, int)):
        params = {'pocket48_phonenum': subscriptor}
    else:
        return False

    try:
        s, _ = Subscriptor.get_or_create(**params)
        for mid in member_ids:
            LiveSubscription.get_or_create(
                    subscriptor=s, member=Member.get(member_id=mid))
    except peewee.OperationalError:
        return False
    return True
models.py 文件源码 项目:sentinel-old 作者: monacocoin-net 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def sync(self, monacoCoind):
        golist = monacoCoind.rpc_command('gobject', 'list')

        # objects which are removed from the network should be removed from the DB
        try:
            for purged in self.purged_network_objects(list(golist.keys())):
                # SOMEDAY: possible archive step here
                purged.delete_instance(recursive=True, delete_nullable=True)

            for item in golist.values():
                (go, subobj) = self.import_gobject_from_monacoCoind(monacoCoind, item)
        except (peewee.InternalError, peewee.OperationalError, peewee.ProgrammingError) as e:
            printdbg("Got an error upon import: %s" % e)
aryas_orm.py 文件源码 项目:aryas 作者: lattkkthxbbye 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def drop_all_tables(self):
        """
        Drops all tables in the database.
        """
        try:
            self.db.drop_tables([self.models.User, self.models.Message, self.models.Channel, self.models.Server,
                                 self.models.LoveTransaction], safe=True)
        except OperationalError as e:
            self.config.logger.error(e)
statistics.py 文件源码 项目:aryas 作者: lattkkthxbbye 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def on_message(self, msg: discord.Message):
        """
        Records the message and sender in the database. Also
        increments the users total messages.
        :param msg: the message
        """
        if not msg.channel.is_private:
            try:
                # append embeds list to message
                body = msg.content
                if msg.embeds:
                    body += '\n' + str(msg.embeds)

                user = self.orm.User.get_or_create(
                    discord_id=msg.author.id
                )[0]

                # Make sure to update the user so all relevant info is there
                update_user_fields(user, msg.author)

                server = self.orm.Server.get_or_create(
                    discord_id=msg.channel.server.id
                )[0]
                channel = self.orm.Channel.get_or_create(
                    discord_id=msg.channel.id,
                    server=server
                )[0]
                self.orm.Message.create(
                    discord_id=msg.id,
                    user=user,
                    channel=channel,
                    body=body,
                    is_command=is_command(self.bot, msg.content),
                    is_embed=True if msg.embeds else False
                )
            except OperationalError as e:
                self.config.logger.error(e)
test_migrator.py 文件源码 项目:peewee-moves 作者: timster 项目源码 文件源码 阅读 49 收藏 0 点赞 0 评论 0
def test_execute_sql(tmpdir):
    manager = DatabaseManager('sqlite:///:memory:', directory=tmpdir)

    with manager.migrator.create_table('awesome') as table:
        table.primary_key('id')
        table.char('name')

    manager.migrator.execute_sql('select * from awesome')
    with pytest.raises(peewee.OperationalError):
        manager.migrator.execute_sql('select * from notable')
app.py 文件源码 项目:autobahn-sync 作者: Scille 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def startup_library_service():
    wamp = autobahn_sync.AutobahnSync()
    wamp.run()
    db = pw.SqliteDatabase('books.db')

    class Book(pw.Model):
        title = pw.CharField()
        author = pw.CharField()

        class Meta:
            database = db

    try:
        db.create_table(Book)
    except pw.OperationalError:
        pass

    @wamp.register('com.library.get_book')
    def get_book(id):
        try:
            b = Book.get(id=id)
        except pw.DoesNotExist:
            return {'_error': "Doesn't exist"}
        return {'id': id, 'title': b.title, 'author': b.author}

    @wamp.register('com.library.new_book')
    def new_book(title, author):
        book = Book(title=title, author=author)
        book.save()
        wamp.session.publish('com.library.book_created', book.id)
        return {'id': book.id}
database.py 文件源码 项目:paper-to-git 作者: maxking 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def _post_initialization(self):
        from papergit.models import PaperDoc, PaperFolder, Sync
        try:
            self.db.create_tables([PaperDoc, PaperFolder, Sync])
        except OperationalError as e:
            if "already exists" in str(e):
                return
            raise
dbmanager.py 文件源码 项目:yt2audiobot 作者: gise88 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def initialize_db(path, root_username):
    db = get_database()
    _init_and_connect(db, path)
    predicate = AuthorizedUser.username == root_username

    try:
        _check_root(predicate)
    except peewee.OperationalError as e:
        for table in USER_DB_MODELS:
            if table.table_exists():
                # some tables exist but some others don't
                raise Exception('ERROR: %s - but %s exists' % (e, table.__name__))
        _drop_tables(db)
        _create_tables(db)
    except (RootDoesNotExistException, RootIsConfiguredIncorrectlyException) as e:
        user_answer = input(
            '%sWarning:  %s\nSomething went wrong in the database and seems to '
            'be missing the root user (or something else)!\nNeed to drop all tables and '
            'recreate them all.\n\nDo you want to continue? [Type \'yes\' to proceed] %s' % (
                TermColors.WARNING,
                str(e),
                TermColors.ENDC
            ))
        if user_answer == 'yes':
            _drop_tables(db)
            _create_tables(db)
        else:
            exit(1)

    _initialize_root(predicate, root_username)
    _verify_migrations(db)
api_db_operation.py 文件源码 项目:Malicious_Domain_Whois 作者: h-j-13 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def get_server_ip(self):
        try:
            query_results = svr_ip.select(
                    svr_ip.svr_name, svr_ip.ip, svr_ip.port_available
                ).where(
                    svr_ip.port_available!=None
                )
            return query_results
        except peewee.OperationalError as e:
            raise e

    # ??proxy_ip ??
api_db_operation.py 文件源码 项目:Malicious_Domain_Whois 作者: h-j-13 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def get_proxy_ip(self):
        try:
            query_results = proxy.select(
                    proxy.whois_server_ip, proxy.ip, proxy.port, proxy.mode, proxy.speed
            ).where(
                    proxy.speed != None, proxy.speed < 1
            )
            return query_results
        except peewee.OperationalError as e:
            raise e
db_operation.py 文件源码 项目:Malicious_Domain_Whois 作者: h-j-13 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def get_server_ip(self):
        try:
            query_results = svr_ip.select(
                    svr_ip.svr_name, svr_ip.ip, svr_ip.port_available
                ).where(
                    svr_ip.port_available!=None
                )
            return query_results
        except peewee.OperationalError as e:
            raise e
db_operation.py 文件源码 项目:Malicious_Domain_Whois 作者: h-j-13 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def get_not_deal_domains(self, table_num, finished_tld):
        try:
            result_list = []
            for tld in finished_tld:
                query_results = self.model_list[table_num].select(
                    self.model_list[table_num].domain
                ).where(
                    self.model_list[table_num].flag == -100,
                    self.model_list[table_num].tld == tld
                ).limit(1000)
                for result in query_results:
                    result_list.append(result.domain)
            # str_eval = """self.model_list[table_num].select(
            #         self.model_list[table_num].domain
            # ).where(
            #         self.model_list[table_num].flag == -100).where(
            # """
            # for tld in finished_tld:
            #     str_eval += "self.model_list[table_num].tld == '{tld}'|".format(tld=str(tld))
            # str_eval = str_eval.strip('|') + ').limit(10000)'
            # # print str_eval
            # query_results = eval(str_eval)
            # return query_results
            return result_list
        except peewee.OperationalError as e:
            raise e

    # ??whois??
db_operation.py 文件源码 项目:Malicious_Domain_Whois 作者: h-j-13 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def insert_whois_info(self, **domain_whois):
        try:
            table_num = get_table_num(domain_whois['domain_hash'])
            event = self.model_list[table_num].insert(
                domain_hash=domain_whois['domain_hash'],
                domain=domain_whois['domain'],
                tld=domain_whois['domain'].split('.')[-1],
                flag=domain_whois['flag'],
                domain_status=domain_whois['domain_status'],
                sponsoring_registrar=domain_whois['sponsoring_registrar'],
                top_whois_server=domain_whois['top_whois_server'],
                sec_whois_server=domain_whois['sec_whois_server'],
                reg_name=domain_whois['reg_name'],
                reg_phone=domain_whois['reg_phone'],
                reg_email=domain_whois['reg_email'],
                org_name=domain_whois['org_name'],
                name_server=domain_whois['name_server'],
                creation_date=domain_whois['creation_date'],
                expiration_date=domain_whois['expiration_date'],
                updated_date=domain_whois['updated_date'],
                insert_time=domain_whois['insert_time'],
                details=domain_whois['details'],
                whois_hash=domain_whois['whois_hash']
            )
            event.execute()
        except peewee.OperationalError as e:
            print e
        except TableChoiceError as e:
            print e

    # ?????whois??
db_operation.py 文件源码 项目:Malicious_Domain_Whois 作者: h-j-13 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def delete_whois_info(self, domain):
        try:
            domain_hash = hash(domain)
            table_num = get_table_num(domain_hash)
            event = self.model_list[table_num].delete().where(
                self.model_list[table_num].domain_hash == domain_hash,
                self.model_list[table_num].domain == domain
            )
            event.execute()
        except peewee.OperationalError as e:
            print e


问题


面经


文章

微信
公众号

扫码关注公众号