本文整理汇总了Python中sqlalchemy.exc.SQLAlchemyError方法的典型用法代码示例。如果您正苦于以下问题:Python exc.SQLAlchemyError方法的具体用法?Python exc.SQLAlchemyError怎么用?Python exc.SQLAlchemyError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sqlalchemy.exc
的用法示例。
在下文中一共展示了exc.SQLAlchemyError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: post
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import SQLAlchemyError [as 别名]
def post(self):
self.parser.add_argument("nickname", type=str, location="json", required=True)
self.parser.add_argument("signature", type=str, location="json", required=True)
args = self.parser.parse_args()
profile = ProfilesModel(nickname=args.nickname, signature=args.signature)
try:
db.session.add(profile)
db.session.commit()
except SQLAlchemyError as e:
current_app.logger.error(e)
db.session.rollback()
return pretty_result(code.DB_ERROR, '数据库错误!')
else:
return pretty_result(code.OK)
示例2: get
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import SQLAlchemyError [as 别名]
def get(id):
id = hash_ids.decode(id)
if not id: abort(404)
try:
profile = ProfilesModel.query.get(id[0])
if not profile: abort(404)
except SQLAlchemyError as e:
current_app.logger.error(e)
db.session.rollback()
return pretty_result(code.DB_ERROR, '数据库错误!')
else:
item = {
'id': hash_ids.encode(profile.id),
'nickname': profile.nickname,
'signature': profile.signature
}
return pretty_result(code.OK, data=item)
示例3: put
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import SQLAlchemyError [as 别名]
def put(self, id):
self.parser.add_argument("nickname", type=str, location="json", required=True)
self.parser.add_argument("signature", type=str, location="json", required=True)
args = self.parser.parse_args()
id = hash_ids.decode(id)
if not id: abort(404)
try:
profile = ProfilesModel.query.get(id[0])
if not profile: abort(404)
profile.nickname = args.nickname
profile.signature = args.signature
db.session.add(profile)
db.session.commit()
except SQLAlchemyError as e:
current_app.logger.error(e)
db.session.rollback()
return pretty_result(code.DB_ERROR, '数据库错误!')
else:
return pretty_result(code.OK)
示例4: delete
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import SQLAlchemyError [as 别名]
def delete(id):
id = hash_ids.decode(id)
if not id: abort(404)
try:
profile = ProfilesModel.query.get(id[0])
if not profile: abort(404)
db.session.delete(profile)
db.session.commit()
except SQLAlchemyError as e:
current_app.logger.error(e)
db.session.rollback()
return pretty_result(code.DB_ERROR, '数据库错误!')
else:
return pretty_result(code.OK)
示例5: confirm_user
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import SQLAlchemyError [as 别名]
def confirm_user(token):
""" Confirm a user account.
"""
user_obj = pagure.lib.query.search_user(flask.g.session, token=token)
if not user_obj:
flask.flash("No user associated with this token.", "error")
else:
user_obj.token = None
flask.g.session.add(user_obj)
try:
flask.g.session.commit()
flask.flash("Email confirmed, account activated")
return flask.redirect(flask.url_for("auth_login"))
except SQLAlchemyError as err: # pragma: no cover
flask.flash(
"Could not set the account as active in the db, "
"please report this error to an admin",
"error",
)
_log.exception(err)
return flask.redirect(flask.url_for("ui_ns.index"))
示例6: upgrade
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import SQLAlchemyError [as 别名]
def upgrade():
partitions = (
'tags', 'resources', 'resource_properties', 'issues',
'issue_properties', 'auditlog', 'logs', 'emails'
)
for table in partitions:
try:
op.execute('ALTER TABLE `{}` REMOVE PARTITIONING'.format(table))
except SQLAlchemyError as ex:
# Silently ignore errors about removing partitions from a table without partitions
if str(ex).find('1505') != -1:
pass
raise
# ### commands auto generated by Alembic - please adjust! ###
op.create_foreign_key('fk_resource_mapping_child', 'resource_mappings', 'resources', ['child'], ['resource_id'], ondelete='CASCADE')
op.create_foreign_key('fk_resource_mapping_parent', 'resource_mappings', 'resources', ['parent'], ['resource_id'], ondelete='CASCADE')
op.create_foreign_key('fk_resource_property_resource_id', 'resource_properties', 'resources', ['resource_id'], ['resource_id'], ondelete='CASCADE')
op.create_foreign_key('fk_resource_account_id', 'resources', 'accounts', ['account_id'], ['account_id'], ondelete='CASCADE')
op.create_foreign_key('fk_resource_types_resource_type_id', 'resources', 'resource_types', ['resource_type_id'], ['resource_type_id'], ondelete='CASCADE')
op.create_foreign_key('fk_tag_resource_id', 'tags', 'resources', ['resource_id'], ['resource_id'], ondelete='CASCADE')
# ### end Alembic commands ###
开发者ID:RiotGames,项目名称:cloud-inquisitor,代码行数:25,代码来源:e445d703e60f_removing_partitions_adding_foreign_keys.py
示例7: reload_data
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import SQLAlchemyError [as 别名]
def reload_data(self):
"""Reloads the configuration from the database
Returns:
`None`
"""
# We must force a rollback here to ensure that we are working on a fresh session, without any cache
db.session.rollback()
self.__data = {}
try:
for ns in db.ConfigNamespace.all():
self.__data[ns.namespace_prefix] = {x.key: x.value for x in ns.config_items}
except SQLAlchemyError as ex:
if str(ex).find('1146') != -1:
pass
示例8: delete
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import SQLAlchemyError [as 别名]
def delete(self, *, auto_commit=False):
"""Removes a resource from the database
Args:
auto_commit (bool): Automatically commit the transaction. Default: `False`
Returns:
`None`
"""
try:
db.session.delete(self.resource)
if auto_commit:
db.session.commit()
except SQLAlchemyError:
self.log.exception('Failed deleting resource: {}'.format(self.id))
db.session.rollback()
示例9: end
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import SQLAlchemyError [as 别名]
def end(self) -> Query:
""" Get the resulting sqlalchemy `Query` object """
# The query
q = self._from_query()
# Apply every handler
for handler_name, handler in self._handlers_ordered_for_end_method():
if not handler.skip_this_handler:
# Apply the handler
try:
q = handler.alter_query(q, as_relation=self._as_relation)
# Enrich SqlAlchemy errors with MongoSQL context (because it's very difficult to debug its cryptic messages)
except sa_exc.SQLAlchemyError as e:
# Get model name by backtracing MongoQuery objects
model_name = []
mq = self
while mq is not None:
model_name.append(mq.bags.model_name)
mq = mq._parent_mongoquery
model_name = ' -> '.join(reversed(model_name))
# Finally, raise one rich error
raise RuntimeQueryError(f'Error processing MongoQuery({model_name}).{handler_name}: {e}') from e
return q
示例10: _update_db
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import SQLAlchemyError [as 别名]
def _update_db(self, ip, port, delay, alive):
proxy_item = self.session.query(Proxy).filter(Proxy.ip == ip, Proxy.port == port).all()
if len(proxy_item):
# 数据库中已经有这个IP了,更新即可
proxy_item = proxy_item[0]
proxy_item.updated_time = datetime.datetime.now()
proxy_item.times = delay
proxy_item.is_alive = 1 if alive else 0
try:
self.session.add(proxy_item)
self.session.commit()
except SQLAlchemyError, e:
logger.error("Error while update proxy information to database.")
logger.error(e.message)
sys.exit(1)
示例11: clean_dead_proxy
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import SQLAlchemyError [as 别名]
def clean_dead_proxy(self):
try:
logger.info("Start clean dead proxy in db.")
dead_proxy = self.session.query(Proxy).filter(Proxy.is_alive == "0").all()
logger.info("Found {} dead proxy in db.".format(len(dead_proxy)))
for dp in dead_proxy:
self.session.delete(dp)
self.session.commit()
logger.info("Clean done. {} dead proxies cleaned.".format(len(dead_proxy)))
except SQLAlchemyError:
logger.fatal("Error occurred when clean dead proxy from db.")
sys.exit(1)
示例12: test_api_new_issue_raise_db_error
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import SQLAlchemyError [as 别名]
def test_api_new_issue_raise_db_error(self):
""" Test the api_new_issue method of the flask api. """
tests.create_projects(self.session)
tests.create_projects_git(
os.path.join(self.path, "tickets"), bare=True
)
tests.create_tokens(self.session)
tests.create_tokens_acl(self.session)
headers = {"Authorization": "token aaabbbcccddd"}
data = {
"title": "test issue",
"issue_content": "This issue needs attention",
}
with self._app.test_request_context("/") as ctx:
flask.g.session = self.session
flask.g.fas_user = tests.FakeUser(username="foo")
with patch(
"flask.g.session.commit",
MagicMock(side_effect=SQLAlchemyError("DB error")),
):
output = self.app.post(
"/api/0/test/new_issue", data=data, headers=headers
)
self.assertEqual(output.status_code, 400)
data = json.loads(output.get_data(as_text=True))
self.assertDictEqual(
data,
{
"error": "An error occurred at the database "
"level and prevent the action from reaching "
"completion",
"error_code": "EDBERROR",
},
)
示例13: relates_commit
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import SQLAlchemyError [as 别名]
def relates_commit(session, username, commitid, issue, app_url=None):
""" Add a comment to an issue that this commit relates to it. """
url = "../%s" % commitid[:8]
if app_url:
if app_url.endswith("/"):
app_url = app_url[:-1]
project = issue.project.fullname
if issue.project.is_fork:
project = "fork/%s" % project
url = "%s/%s/c/%s" % (app_url, project, commitid[:8])
comment = """ Commit [%s](%s) relates to this ticket""" % (
commitid[:8],
url,
)
try:
pagure.lib.query.add_issue_comment(
session, issue=issue, comment=comment, user=username
)
session.commit()
except pagure.exceptions.PagureException as err:
print(err)
except SQLAlchemyError as err: # pragma: no cover
session.rollback()
_log.exception(err)
示例14: update_user_settings
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import SQLAlchemyError [as 别名]
def update_user_settings():
""" Update the user's settings set in the settings page.
"""
if admin_session_timedout():
if flask.request.method == "POST":
flask.flash("Action canceled, try it again", "error")
return flask.redirect(
flask.url_for("auth_login", next=flask.request.url)
)
user = _get_user(username=flask.g.fas_user.username)
form = pagure.forms.ConfirmationForm()
if form.validate_on_submit():
settings = {}
for key in flask.request.form:
if key == "csrf_token":
continue
settings[key] = flask.request.form[key]
try:
message = pagure.lib.query.update_user_settings(
flask.g.session, settings=settings, user=user.username
)
flask.g.session.commit()
flask.flash(message)
except pagure.exceptions.PagureException as msg:
flask.g.session.rollback()
flask.flash(msg, "error")
except SQLAlchemyError as err: # pragma: no cover
flask.g.session.rollback()
flask.flash(str(err), "error")
return flask.redirect(flask.url_for("ui_ns.user_settings"))
示例15: remove_user_email
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import SQLAlchemyError [as 别名]
def remove_user_email():
""" Remove the specified email from the logged in user.
"""
if admin_session_timedout():
return flask.redirect(
flask.url_for("auth_login", next=flask.request.url)
)
user = _get_user(username=flask.g.fas_user.username)
if len(user.emails) == 1:
flask.flash("You must always have at least one email", "error")
return flask.redirect(flask.url_for("ui_ns.user_settings"))
form = pagure.forms.UserEmailForm()
if form.validate_on_submit():
email = form.email.data
useremails = [mail.email for mail in user.emails]
if email not in useremails:
flask.flash(
"You do not have the email: %s, nothing to remove" % email,
"error",
)
return flask.redirect(flask.url_for("ui_ns.user_settings"))
for mail in user.emails:
if mail.email == email:
user.emails.remove(mail)
break
try:
flask.g.session.commit()
flask.flash("Email removed")
except SQLAlchemyError as err: # pragma: no cover
flask.g.session.rollback()
_log.exception(err)
flask.flash("Email could not be removed", "error")
return flask.redirect(flask.url_for("ui_ns.user_settings"))