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
python类OperationalError()的实例源码
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()