本文整理汇总了Python中sqlalchemy.exc.IntegrityError方法的典型用法代码示例。如果您正苦于以下问题:Python exc.IntegrityError方法的具体用法?Python exc.IntegrityError怎么用?Python exc.IntegrityError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sqlalchemy.exc
的用法示例。
在下文中一共展示了exc.IntegrityError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: add_user
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import IntegrityError [as 别名]
def add_user(cls, identifier: str, password: str, password_encrypted: bool = False) -> None:
"""新增用户。当用户已存在时,抛出ValueError。
:param identifier: 学号或教工号
:param password: 密码
:param password_encrypted: 密码是否已经被加密过了(否则会被二次加密)
"""
if not password_encrypted:
password_hash = generate_password_hash(password)
else:
password_hash = password
user = User(identifier=identifier, password=password_hash, create_time=datetime.datetime.now())
db_session.add(user)
try:
db_session.commit()
except IntegrityError as e:
raise AlreadyRegisteredError from e
示例2: test_unique_identities
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import IntegrityError [as 别名]
def test_unique_identities(self):
"""Check if there is only one tuple with the same values"""
id1 = Identity(id='A', name='John Smith', email='jsmith@example.com',
username='jsmith', source='scm')
id2 = Identity(id='B', name='John Smith', email='jsmith@example.com',
username='jsmith', source='scm')
with self.assertRaisesRegex(IntegrityError, DUP_CHECK_ERROR):
self.session.add(id1)
self.session.add(id2)
self.session.commit()
self.session.rollback()
# Changing an property should not raise any error
id2.source = 'mls'
self.session.add(id1)
self.session.add(id2)
self.session.commit()
self.assertNotEqual(id1.id, id2.id)
示例3: test_unique_enrollments
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import IntegrityError [as 别名]
def test_unique_enrollments(self):
"""Check if there is only one tuple with the same values"""
with self.assertRaisesRegex(IntegrityError, DUP_CHECK_ERROR):
uid = UniqueIdentity(uuid='John Smith')
self.session.add(uid)
org = Organization(name='Example')
self.session.add(org)
rol1 = Enrollment(uidentity=uid, organization=org)
rol2 = Enrollment(uidentity=uid, organization=org)
self.session.add(rol1)
self.session.add(rol2)
self.session.commit()
示例4: generate_fake
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import IntegrityError [as 别名]
def generate_fake(count=100):
from sqlalchemy.exc import IntegrityError
from random import seed
import forgery_py
seed()
for i in range(count):
u = User(email=forgery_py.internet.email_address(),
username=forgery_py.internet.user_name(True),
password=forgery_py.lorem_ipsum.word(),
confirmed=True,
name=forgery_py.name.full_name(),
location=forgery_py.address.city(),
about_me=forgery_py.lorem_ipsum.sentence(),
member_since=forgery_py.date.date(True))
db.session.add(u)
try:
db.session.commit()
except IntegrityError:
db.session.rollback()
示例5: delete_alias
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import IntegrityError [as 别名]
def delete_alias(alias: Alias, user: User):
Alias.delete(alias.id)
db.session.commit()
# save deleted alias to either global or domain trash
if alias.custom_domain_id:
try:
DomainDeletedAlias.create(
user_id=user.id, email=alias.email, domain_id=alias.custom_domain_id
)
db.session.commit()
except IntegrityError:
LOG.error(
"alias %s domain %s has been added before to DeletedAlias",
alias.email,
alias.custom_domain_id,
)
db.session.rollback()
else:
try:
DeletedAlias.create(email=alias.email)
db.session.commit()
except IntegrityError:
LOG.error("alias %s has been added before to DeletedAlias", alias.email)
db.session.rollback()
示例6: delete
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import IntegrityError [as 别名]
def delete(cls, obj_id):
# Put all aliases belonging to this mailbox to global trash
try:
for alias in Alias.query.filter_by(mailbox_id=obj_id):
# special handling for alias that has several mailboxes and has mailbox_id=obj_id
if len(alias.mailboxes) > 1:
# use the first mailbox found in alias._mailboxes
first_mb = alias._mailboxes[0]
alias.mailbox_id = first_mb.id
alias._mailboxes.remove(first_mb)
else:
# only put aliases that have mailbox as a single mailbox into trash
DeletedAlias.create(email=alias.email)
db.session.commit()
# this can happen when a previously deleted alias is re-created via catch-all or directory feature
except IntegrityError:
LOG.error("Some aliases have been added before to DeletedAlias")
db.session.rollback()
cls.query.filter(cls.id == obj_id).delete()
db.session.commit()
示例7: execute_query
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import IntegrityError [as 别名]
def execute_query(instance: PluginInstance, sql_query: Union[str, Query],
rows_as_dict: bool = False) -> web.Response:
try:
res: ResultProxy = instance.inst_db.execute(sql_query)
except exc.IntegrityError as e:
return resp.sql_integrity_error(e, sql_query)
except exc.OperationalError as e:
return resp.sql_operational_error(e, sql_query)
data = {
"ok": True,
"query": str(sql_query),
}
if res.returns_rows:
row: RowProxy
data["rows"] = [({key: check_type(value) for key, value in row.items()}
if rows_as_dict
else [check_type(value) for value in row])
for row in res]
data["columns"] = res.keys()
else:
data["rowcount"] = res.rowcount
if res.is_insert:
data["inserted_primary_key"] = res.inserted_primary_key
return web.json_response(data)
示例8: insert_to_db
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import IntegrityError [as 别名]
def insert_to_db(self):
db.session.add(self)
try:
db.session.commit()
except IntegrityError:
db.session.rollback()
flag = False
while flag == False:
integration = Integration.query.filter_by(integration_id=self.integration_id).first()
if integration is not None:
self.integration_id = generate_integration_id()
db.session.add(self)
try:
db.session.commit()
flag = True
except IntegrityError:
db.session.rollback()
flag = False
else:
flag = True
return True
示例9: add_naming_convention
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import IntegrityError [as 别名]
def add_naming_convention(scope, regexp, convention_type, session=None):
"""
add a naming convention for a given scope
:param scope: the name for the scope.
:param regexp: the regular expression to validate the name.
:param convention_type: the did_type on which the regexp should apply.
:param session: The database session in use.
"""
# validate the regular expression
try:
compile(regexp)
except error:
raise RucioException('Invalid regular expression %s!' % regexp)
new_convention = models.NamingConvention(scope=scope,
regexp=regexp,
convention_type=convention_type)
try:
new_convention.save(session=session)
except IntegrityError:
raise Duplicate('Naming convention already exists!')
except:
raise RucioException(str(format_exc()))
示例10: delete_distances
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import IntegrityError [as 别名]
def delete_distances(src_rse_id=None, dest_rse_id=None, session=None):
"""
Delete distances with the given RSE ids.
:param src_rse_id: The source RSE ID.
:param dest_rse_id: The destination RSE ID.
:param session: The database session to use.
"""
try:
query = session.query(Distance)
if src_rse_id:
query = query.filter(Distance.src_rse_id == src_rse_id)
if dest_rse_id:
query = query.filter(Distance.dest_rse_id == dest_rse_id)
query.delete()
except IntegrityError as error:
raise exception.RucioException(error.args)
示例11: update_distances
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import IntegrityError [as 别名]
def update_distances(src_rse_id=None, dest_rse_id=None, parameters=None, session=None):
"""
Update distances with the given RSE ids.
:param src_rse_id: The source RSE ID.
:param dest_rse_id: The destination RSE ID.
:param parameters: A dictionnary with property
:param session: The database session to use.
"""
params = {}
for key in parameters:
if key in ['ranking', 'agis_distance', 'geoip_distance', 'active', 'submitted', 'finished', 'failed', 'transfer_speed', 'packet_loss', 'latency', 'mbps_file', 'mbps_link', 'queued_total', 'done_1h', 'done_6h']:
params[key] = parameters[key]
try:
query = session.query(Distance)
if src_rse_id:
query = query.filter(Distance.src_rse_id == src_rse_id)
if dest_rse_id:
query = query.filter(Distance.dest_rse_id == dest_rse_id)
query.update(params)
except IntegrityError as error:
raise exception.RucioException(error.args)
示例12: set_transfer_update_time
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import IntegrityError [as 别名]
def set_transfer_update_time(external_host, transfer_id, update_time=datetime.datetime.utcnow(), session=None):
"""
Update the state of a request. Fails silently if the transfer_id does not exist.
:param external_host: Selected external host as string in format protocol://fqdn:port
:param transfer_id: External transfer job id as a string.
:param update_time: Time stamp.
:param session: Database session to use.
"""
record_counter('core.request.set_transfer_update_time')
try:
rowcount = session.query(models.Request).filter_by(external_id=transfer_id, state=RequestState.SUBMITTED).update({'updated_at': update_time}, synchronize_session=False)
except IntegrityError as error:
raise RucioException(error.args)
if not rowcount:
raise UnsupportedOperation("Transfer %s doesn't exist or its status is not submitted." % (transfer_id))
示例13: __set_transfer_state
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import IntegrityError [as 别名]
def __set_transfer_state(external_host, transfer_id, new_state, session=None):
"""
Update the state of a transfer. Fails silently if the transfer_id does not exist.
:param external_host: Selected external host as string in format protocol://fqdn:port
:param transfer_id: External transfer job id as a string.
:param new_state: New state as string.
:param session: Database session to use.
"""
record_counter('core.request.set_transfer_state')
try:
rowcount = session.query(models.Request).filter_by(external_id=transfer_id).update({'state': new_state, 'updated_at': datetime.datetime.utcnow()}, synchronize_session=False)
except IntegrityError as error:
raise RucioException(error.args)
if not rowcount:
raise UnsupportedOperation("Transfer %s on %s state %s cannot be updated." % (transfer_id, external_host, new_state))
示例14: add_dids_to_followed
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import IntegrityError [as 别名]
def add_dids_to_followed(dids, account, session=None):
"""
Bulk mark datasets as followed
:param dids: A list of dids.
:param account: The account owner.
:param session: The database session in use.
"""
try:
for did in dids:
# Get the did details corresponding to the scope and name passed.
did = session.query(models.DataIdentifier).filter_by(scope=did['scope'], name=did['name']).one()
# Add the queried to the followed table.
new_did_followed = models.DidsFollowed(scope=did.scope, name=did.name, account=account,
did_type=did.did_type)
new_did_followed.save(session=session, flush=False)
session.flush()
except IntegrityError as error:
raise exception.RucioException(error.args)
示例15: trigger_event
# 需要导入模块: from sqlalchemy import exc [as 别名]
# 或者: from sqlalchemy.exc import IntegrityError [as 别名]
def trigger_event(scope, name, event_type, payload, session=None):
"""
Records changes occuring in the did to the FollowEvents table
:param scope: The scope name.
:param name: The data identifier name.
:param event_type: The type of event affecting the did.
:param payload: Any message to be stored along with the event.
:param session: The database session in use.
"""
try:
dids = session.query(models.DidsFollowed).filter_by(scope=scope, name=name).all()
for did in dids:
# Create a new event using teh specified parameters.
new_event = models.FollowEvents(scope=scope, name=name, account=did.account,
did_type=did.did_type, event_type=event_type, payload=payload)
new_event.save(session=session, flush=False)
session.flush()
except IntegrityError as error:
raise exception.RucioException(error.args)