我们从Python开源项目中,提取了以下45个代码示例,用于说明如何使用peewee.OperationalError()。
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)
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()
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
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()
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)
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()
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
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 ????
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!")
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)
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
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()
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 :(")
def retry_if_peewee_error(cls, error): return isinstance(error, (peewee.OperationalError, peewee.InterfaceError))
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
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)
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)
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)
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')
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}
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
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)
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 ??
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
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
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??
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??
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
def set_whois_flag(self, domain, flag): try: domain_hash = hash(domain) table_num = get_table_num(domain_hash) event = self.model_list[table_num].update( flag=flag ).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
def query_all_whois_addr(self): try: query_results = self.whois_addr_model.select().where( self.whois_addr_model.addr is not None ) return query_results except peewee.OperationalError as e: print e # ??whois_server???tld
def get_tld(self, whois_server): try: query_results = self.whois_addr_model.select( self.whois_addr_model.tld ).where( peewee.R('addr like %s', '%,' + whois_server) | peewee.R('addr like %s', whois_server + ',%') | peewee.R('addr = %s', whois_server), self.whois_addr_model.addr <> '' ) return query_results except peewee.OperationalError as e: raise e
def setup_database(): db.connect() try: db.create_tables([User, Module]) except peewee.OperationalError as e: print(e)
def create_user(): # Create new User record using Peewee module class # Note: right now, this does not prevent empty strings being passed to API try: new_user = User( email = request.form.get('email'), password = request.form.get('password'), first_name = request.form.get('first_name'), last_name = request.form.get('last_name'), is_admin = bool(request.form.get('is_admin')) ) new_user.set_password(new_user.password) new_user.save() # Deal with exception if a required field was null # by returning 400 response ''' except peewee.OperationalError: return dict( code=400, msg="Bad request: missing data" ), 400 # Deal with exception that arises if email was not unique except peewee.IntegrityError: return dict( code=10000, msg="Email already exists" ), 409 return new_user.to_hash()
def client(request): import memesocial memesocial.init('memesocial.config.testingConfig') client = memesocial.app.test_client() with memesocial.app.app_context(): try: memesocial.db.drop_tables(memesocial.all_tables) except OperationalError: # This occurs when the table does not exist pass memesocial.db.create_tables(memesocial.all_tables) return client
def get_conn(self): if self.closed: raise OperationalError('Database pool has not been initialized') return AioConnection(self.pool.acquire(), autocommit=self.autocommit, autorollback=self.autorollback, exception_wrapper=self.exception_wrapper)
def connect(self, safe=True): if self.deferred: raise OperationalError('Database has not been initialized') if not self.closed: if safe: return raise OperationalError('Connection already open') with self.exception_wrapper: self.pool = await self._connect(self.database, **self.connect_kwargs) self.closed = False
def run(self): while not self.event.is_set(): try: self.process_pending_jobs() except peewee.OperationalError: log.warning('Lost database connection') except: log.exception('Error during submission') self.event.wait(self.interval)
def is_operational_error(exception): return isinstance(exception, peewee.OperationalError)
def _install_db(self): drop_tables = input("Do you want to drop existing tables? [y/N]") == "y" try: result = self._install_db_tables(drop_tables = drop_tables) if result: print("Database installation OK") except OperationalError as exc: print("An exception occured during tables creation:") print(str(exc))
def connect(self): """ Connect to the database, return True on success. """ with self.num_connections_lock: assert self.num_connections >= 0 self.num_connections += 1 if self.num_connections == 1: try: self.database.connect() if DEBUG: LOG.debug("[db] Database connected") except OperationalError as exc: _DbConnector.log_error("connect", exc) self.num_connections -= 1 return False return True
def close(self): """ Close the database connection, return True on success. """ with self.num_connections_lock: self.num_connections -= 1 if self.num_connections == 0: try: self.database.close() if DEBUG: LOG.debug("[db] Database closed") except OperationalError as exc: _DbConnector.log_error("close", exc) return False return True
def import_gobject_from_monacoCoind(self, monacoCoind, rec): import monacoCoinlib import inflection object_hex = rec['DataHex'] object_hash = rec['Hash'] gobj_dict = { 'object_hash': object_hash, 'object_fee_tx': rec['CollateralHash'], 'absolute_yes_count': rec['AbsoluteYesCount'], 'abstain_count': rec['AbstainCount'], 'yes_count': rec['YesCount'], 'no_count': rec['NoCount'], } # shim/monacoCoind conversion object_hex = monacoCoinlib.SHIM_deserialise_from_monacoCoind(object_hex) objects = monacoCoinlib.deserialise(object_hex) subobj = None obj_type, dikt = objects[0:2:1] obj_type = inflection.pluralize(obj_type) subclass = self._meta.reverse_rel[obj_type].model_class # set object_type in govobj table gobj_dict['object_type'] = subclass.govobj_type # exclude any invalid model data from monacoCoind... valid_keys = subclass.serialisable_fields() subdikt = {k: dikt[k] for k in valid_keys if k in dikt} # get/create, then sync vote counts from monacoCoind, with every run govobj, created = self.get_or_create(object_hash=object_hash, defaults=gobj_dict) if created: printdbg("govobj created = %s" % created) count = govobj.update(**gobj_dict).where(self.id == govobj.id).execute() if count: printdbg("govobj updated = %d" % count) subdikt['governance_object'] = govobj # get/create, then sync payment amounts, etc. from monacoCoind - monacoCoind is the master try: subobj, created = subclass.get_or_create(object_hash=object_hash, defaults=subdikt) except (peewee.OperationalError, peewee.IntegrityError) as e: # in this case, vote as delete, and log the vote in the DB printdbg("Got invalid object from monacoCoind! %s" % e) if not govobj.voted_on(signal=VoteSignals.delete, outcome=VoteOutcomes.yes): govobj.vote(monacoCoind, VoteSignals.delete, VoteOutcomes.yes) return (govobj, None) if created: printdbg("subobj created = %s" % created) count = subobj.update(**subdikt).where(subclass.id == subobj.id).execute() if count: printdbg("subobj updated = %d" % count) # ATM, returns a tuple w/gov attributes and the govobj return (govobj, subobj)
def main(): db.db.connect() try: db.db.create_tables([db.Conversation, db.User, db.IsMod, db.Vote]) except pw.OperationalError: pass updater = Updater(settings.KEY) dispatcher = updater.dispatcher dispatcher.add_handler(CommandHandler('start', start)) dispatcher.add_handler(CommandHandler('help', send_help_message)) dispatcher.add_handler(CommandHandler('auto', set_auto)) dispatcher.add_handler(CommandHandler('location', set_location, pass_args=True)) dispatcher.add_handler(CommandHandler('set_account', set_account)) dispatcher.add_handler(CommandHandler('unlink', unlink)) dispatcher.add_handler(CommandHandler('matches', send_matches)) dispatcher.add_handler(CallbackQueryHandler(inline.do_press_inline_button, pass_job_queue=True)) dispatcher.add_handler(MessageHandler(Filters.text, message_handler, pass_job_queue=True)) dispatcher.add_handler(MessageHandler(Filters.location, update_location)) dispatcher.add_handler(CommandHandler('new_vote', start_vote_session, pass_job_queue=True)) dispatcher.add_handler(CommandHandler('timeout', set_timeout, pass_args=True)) dispatcher.add_handler(CommandHandler('about', send_about)) # Chat functionality dispatcher.add_handler(CommandHandler('poll_msgs', chat.poll_messages, pass_args=True)) dispatcher.add_handler(CommandHandler('poll_unanswered', chat.poll_unanswered_messages, pass_args=True)) dispatcher.add_handler(CommandHandler('unblock', chat.unblock)) # Settings dispatcher.add_handler(CommandHandler('set_setting', admin.set_setting, pass_args=True)) dispatcher.add_handler(CommandHandler('list_settings', admin.list_settings)) dispatcher.add_handler(CommandHandler('help_settings', admin.help_settings)) # Moderators dispatcher.add_handler(CommandHandler('make_me_a_mod', admin.make_me_a_mod)) inline_caps_handler = InlineQueryHandler(inline.inline_preview) dispatcher.add_handler(inline_caps_handler) dispatcher.add_handler(MessageHandler(Filters.command, custom_command_handler)) dispatcher.add_error_handler(error_callback) updater.start_polling() updater.idle()