Python peewee.IntegrityError() Examples
The following are 30
code examples of peewee.IntegrityError().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
peewee
, or try the search function
.
Example #1
Source File: test_indexes.py From open-syllabus-project with Apache License 2.0 | 6 votes |
def test_unique_pairs(add_subfield, add_doc): """ Don't allow duplicate links between the same field -> document. """ s = add_subfield() d = add_doc() Subfield_Document.create( subfield=s, document=d, offset=1, snippet='abc' ) with pytest.raises(IntegrityError): Subfield_Document.create( subfield=s, document=d, offset=2, snippet='def' )
Example #2
Source File: user.py From quay with Apache License 2.0 | 6 votes |
def post(self): """ Star a repository. """ user = get_authenticated_user() req = request.get_json() namespace = req["namespace"] repository = req["repository"] repo = model.repository.get_repository(namespace, repository) if repo: try: model.repository.star_repository(user, repo) except IntegrityError: pass return {"namespace": namespace, "repository": repository,}, 201
Example #3
Source File: image.py From quay with Apache License 2.0 | 6 votes |
def find_or_create_derived_storage( source_image, transformation_name, preferred_location, varying_metadata=None ): existing = find_derived_storage_for_image(source_image, transformation_name, varying_metadata) if existing is not None: return existing uniqueness_hash = _get_uniqueness_hash(varying_metadata) trans = ImageStorageTransformation.get(name=transformation_name) new_storage = storage.create_v1_storage(preferred_location) try: derived = DerivedStorageForImage.create( source_image=source_image, derivative=new_storage, transformation=trans, uniqueness_hash=uniqueness_hash, ) except IntegrityError: # Storage was created while this method executed. Just return the existing. ImageStoragePlacement.delete().where(ImageStoragePlacement.storage == new_storage).execute() new_storage.delete_instance() return find_derived_storage_for_image(source_image, transformation_name, varying_metadata) return derived
Example #4
Source File: login.py From quay with Apache License 2.0 | 6 votes |
def _attach_service(login_service, user_obj, lid, lusername): """ Attaches the given user account to the given service, with the given service user ID and service username. """ metadata = { "service_username": lusername, } try: model.user.attach_federated_login( user_obj, login_service.service_id(), lid, metadata=metadata ) return _oauthresult(user_obj=user_obj) except IntegrityError: err = "%s account %s is already attached to a %s account" % ( login_service.service_name(), lusername, app.config["REGISTRY_TITLE_SHORT"], ) return _oauthresult(service_name=login_service.service_name(), error_message=err)
Example #5
Source File: model.py From torpeewee with MIT License | 6 votes |
def get_or_create(cls, **kwargs): defaults = kwargs.pop('defaults', {}) query = cls.select() for field, value in kwargs.items(): query = query.where(getattr(cls, field) == value) try: result = await query.get(), False except cls.DoesNotExist: try: if defaults: kwargs.update(defaults) with cls._meta.database.atomic(): result = await cls.create(**kwargs), True except IntegrityError as exc: try: result = await query.get(), False except cls.DoesNotExist: raise exc return result
Example #6
Source File: model.py From torpeewee with MIT License | 6 votes |
def get_or_create(self, **kwargs): defaults = kwargs.pop('defaults', {}) query = self.model_class.select().bind(self.database) for field, value in kwargs.items(): query = query.where(getattr(self.model_class, field) == value) try: result = await query.get(), False except self.model_class.DoesNotExist: try: if defaults: kwargs.update(defaults) result = await self.create(**kwargs), True except IntegrityError as exc: try: result = await query.get(), False except self.model_class.DoesNotExist: raise exc return result
Example #7
Source File: rss.py From carebot with MIT License | 6 votes |
def write(self, stories, team=None): # TODO # this should be abstracted here and in spreadsheet.py new_stories = [] for story in stories: try: story = Story.create( name = story['name'], slug = story['slug'], date = story['date'], url = story['url'], team = team ) new_stories.append(story) except IntegrityError: # Story probably already exists. logger.info('Not adding %s to database: probably already exists' % (story['name'])) return new_stories
Example #8
Source File: npr_pocky.py From carebot with MIT License | 6 votes |
def write(self, stories, team=None): """ Save rows to the database """ new_stories = [] for story in stories: slug = story['official flavor description'] + ' - ' + story['taster'] try: story = Story.create( name=story['name'].strip(), slug=slug, date=PockyScraper.parse_date(story['date tasted']), story_type='pocky', team=team, ) logger.info('Added {0}'.format(story.name)) new_stories.append(story) except IntegrityError: # Story probably already exists. logger.info('Not adding %s to database: probably already exists' % (slug)) pass return new_stories
Example #9
Source File: test_indexes.py From open-syllabus-project with Apache License 2.0 | 6 votes |
def test_unique_pairs(add_doc, add_institution): """ Don't allow duplicate links between the same doc -> inst pair. """ inst = add_institution() doc = add_doc() Institution_Document.create( institution=inst, document=doc, ) with pytest.raises(IntegrityError): Institution_Document.create( institution=inst, document=doc, )
Example #10
Source File: new_request_model.py From openrasp-iast with Apache License 2.0 | 6 votes |
def put(self, rasp_result_ins): """ 将rasp_result_ins序列化并插入数据表 Returns: 插入成功返回True, 重复返回False Raises: exceptions.DatabaseError - 数据库错误引发此异常 """ try: data = { "data": rasp_result_ins.dump(), "data_hash": rasp_result_ins.get_hash() } await peewee_async.create_object(self.ResultList, **data) except peewee.IntegrityError as e: return False except asyncio.CancelledError as e: raise e except Exception as e: Logger().critical("DB error in method put!", exc_info=e) else: return True
Example #11
Source File: model.py From aiopeewee with MIT License | 6 votes |
def get_or_create(cls, **kwargs): defaults = kwargs.pop('defaults', {}) query = cls.select() for field, value in kwargs.items(): if '__' in field: query = query.filter(**{field: value}) else: query = query.where(getattr(cls, field) == value) try: return await query.get(), False except cls.DoesNotExist: try: params = dict((k, v) for k, v in kwargs.items() if '__' not in k) params.update(defaults) async with cls._meta.database.atomic(): return await cls.create(**params), True except IntegrityError as exc: try: return await query.get(), False except cls.DoesNotExist: raise exc
Example #12
Source File: blob.py From quay with Apache License 2.0 | 5 votes |
def get_or_create_blob(digest, size, media_type_name, locations, models_ref): """ Try to find a blob by its digest or create it. """ Blob = models_ref.Blob BlobPlacement = models_ref.BlobPlacement # Get or create the blog entry for the digest. try: blob = get_blob(digest, models_ref) logger.debug("Retrieved blob with digest %s", digest) except Blob.DoesNotExist: blob = Blob.create( digest=_ensure_sha256_header(digest), media_type_id=Blob.media_type.get_id(media_type_name), size=size, ) logger.debug("Created blob with digest %s", digest) # Add the locations to the blob. for location_name in locations: location_id = BlobPlacement.location.get_id(location_name) try: BlobPlacement.create(blob=blob, location=location_id) except IntegrityError: logger.debug("Location %s already existing for blob %s", location_name, blob.id) return blob
Example #13
Source File: cache.py From calm-dsl with Apache License 2.0 | 5 votes |
def sync(cls): """Sync cache by latest data""" def sync_tables(tables): for table in tables: table.sync() click.echo(".", nl=False, err=True) cache_table_map = cls.get_cache_tables() tables = list(cache_table_map.values()) # Inserting version table at start tables.insert(0, Version) try: LOG.info("Updating cache", nl=False) sync_tables(tables) except (OperationalError, IntegrityError): click.echo(" [Fail]") # init db handle once (recreating db if some schema changes are there) LOG.info("Removing existing db and updating cache again") init_db_handle() LOG.info("Updating cache", nl=False) sync_tables(tables) click.echo(" [Done]", err=True)
Example #14
Source File: repositoryactioncount.py From quay with Apache License 2.0 | 5 votes |
def delete_expired_entries(repo, limit=50): """ Deletes expired entries from the RepositoryActionCount table for a specific repository. Returns the number of entries removed. """ threshold_date = datetime.today() - RAC_RETENTION_PERIOD found = list( RepositoryActionCount.select() .where( RepositoryActionCount.repository == repo, RepositoryActionCount.date < threshold_date ) .limit(limit) ) if not found: return 0 assert len(found) <= limit count_removed = 0 for entry in found: try: entry.delete_instance(recursive=False) count_removed += 1 except IntegrityError: continue return count_removed
Example #15
Source File: data.py From kickoff-player with GNU General Public License v3.0 | 5 votes |
def create_single(self, model, kwargs): model = self.get_model(model) try: item = model.create(**kwargs) except IntegrityError: item = None return item
Example #16
Source File: repositoryactioncount.py From quay with Apache License 2.0 | 5 votes |
def store_repository_action_count(repository, day, action_count): """ Stores the action count for a repository for a specific day. Returns False if the repository already has an entry for the specified day. """ try: RepositoryActionCount.create(repository=repository, date=day, count=action_count) return True except IntegrityError: logger.debug("Count already written for repository %s", repository.id) return False
Example #17
Source File: data.py From kickoff-player with GNU General Public License v3.0 | 5 votes |
def update_single(self, model, item, kwargs): model = self.get_model(model) try: kwargs['updated'] = now() query = model.update(**kwargs).where(model.id == item.id) query.execute() except IntegrityError: item = None return item
Example #18
Source File: user.py From quay with Apache License 2.0 | 5 votes |
def update_email(user, new_email, auto_verify=False): try: user.email = new_email user.verified = auto_verify user.save() except IntegrityError: raise DataModelException("E-mail address already used")
Example #19
Source File: cache.py From kickoff-player with GNU General Public License v3.0 | 5 votes |
def create(self, key, value, ttl=0): try: item = Cacheable.create(key=key, value=value.strip(), ttl=ttl) except IntegrityError: item = None return item
Example #20
Source File: tag.py From quay with Apache License 2.0 | 5 votes |
def create_or_update_tag( repo, tag_name, models_ref, manifest_list=None, linked_tag=None, tag_kind="release" ): Tag = models_ref.Tag now_ts = get_epoch_timestamp_ms() tag_kind_id = Tag.tag_kind.get_id(tag_kind) with db_transaction(): try: tag = db_for_update( tag_is_alive( Tag.select().where( Tag.repository == repo, Tag.name == tag_name, Tag.tag_kind == tag_kind_id ), Tag, now_ts, ) ).get() if tag.manifest_list == manifest_list and tag.linked_tag == linked_tag: return tag tag.lifetime_end = now_ts tag.save() except Tag.DoesNotExist: pass try: return Tag.create( repository=repo, manifest_list=manifest_list, linked_tag=linked_tag, name=tag_name, lifetime_start=now_ts, lifetime_end=None, tag_kind=tag_kind_id, ) except IntegrityError: msg = "Tag with name %s and lifetime start %s under repository %s/%s already exists" raise TagAlreadyCreatedException( msg % (tag_name, now_ts, repo.namespace_user, repo.name) )
Example #21
Source File: config_model.py From openrasp-iast with Apache License 2.0 | 5 votes |
def update(self, host_port, config_json): """ 插入或更新一条config数据 Parameters: host_port - str, 配置对应的机器 config_json - str, 配置内容的json Raises: exceptions.DatabaseError - 数据库错误引发此异常 """ host_port_hash = hashlib.md5(host_port.encode("utf-8")).hexdigest() try: self.Config.insert( host_port_hash=host_port_hash, host_port=host_port, config_json=config_json ).execute() except peewee.IntegrityError: self.Config.update( { self.Config.config_json: config_json } ).where( self.Config.host_port_hash == host_port_hash ).execute() except Exception as e: self._handle_exception("DB error in method update!", e)
Example #22
Source File: cache.py From kickoff-player with GNU General Public License v3.0 | 5 votes |
def update(self, item, value, ttl=0): kwargs = { 'value': value.strip(), 'ttl': ttl, 'updated': now() } try: query = Cacheable.update(**kwargs).where(Cacheable.key == item.key) query.execute() except IntegrityError: pass return item
Example #23
Source File: user.py From slim with zlib License | 5 votes |
def new(cls, username, password, *, email=None, nickname=None, is_for_tests=False) -> Optional['User']: values = { 'email': email, 'username': username, 'nickname': nickname, 'is_for_tests': is_for_tests, # 被default自动生成 # 'id': CustomID().to_bin(), # 'time': int(time.time()), } info = cls.gen_password_and_salt(password) values.update(info) try: uid = User.insert(values).execute() u = User.get_by_pk(uid) return u except peewee.IntegrityError as e: # traceback.print_exc() db.rollback() if e.args[0].startswith('duplicate key'): return except peewee.DatabaseError: traceback.print_exc() db.rollback()
Example #24
Source File: npr_spreadsheet.py From carebot with MIT License | 5 votes |
def write(self, stories, team=None): """ Save rows to the database """ new_stories = [] for story in stories: info_from_api = npr_api_scraper.get_story_details(story['story_url']) if not info_from_api: logger.info('Not adding %s to database: could not get story' % (story['story_headline'])) pass exists = Story.select().where(Story.url == story['story_url']) if exists: logger.info('Not adding %s to database: already exists' % (story['story_headline'])) else: try: screenshot_url = screenshotter.get_story_image(story_url=story['story_url']) story = Story.create( name = story['story_headline'].strip(), slug = story['graphic_slug'].strip(), date = info_from_api['date'], story_type = story['graphic_type'].strip(), url = story['story_url'].strip(), image = info_from_api['image'], team = team, screenshot = screenshot_url ) logger.info('Added {0}'.format(story.name.encode("ascii"))) new_stories.append(story) except IntegrityError: # Story probably already exists. logger.info('Not adding %s to database: probably already exists' % (story['story_headline'])) pass return new_stories
Example #25
Source File: sqlfuncs.py From slim with zlib License | 5 votes |
def __exit__(self, exc_type, exc_val, exc_tb): db = self.db if isinstance(exc_val, peewee.IntegrityError): db.rollback() if exc_val.args[0].startswith('duplicate key') or '唯一约束' in exc_val.args[0]: raise AlreadyExists() elif exc_val.args[0].startswith('NOT NULL constraint failed'): raise NotNullConstraintFailed() elif isinstance(exc_val, peewee.DatabaseError): db.rollback() logger.error("database error", exc_val) raise ResourceException("database error") # noinspection PyProtectedMember,PyArgumentList
Example #26
Source File: test_indexes.py From open-syllabus-project with Apache License 2.0 | 5 votes |
def test_unique_pairs(add_text, add_doc, add_citation): """ Don't allow duplicate links between the same text -> syllabus pair. """ t = add_text() d = add_doc() add_citation(text=t, document=d) with pytest.raises(IntegrityError): add_citation(text=t, document=d)
Example #27
Source File: test_indexes.py From open-syllabus-project with Apache License 2.0 | 5 votes |
def test_unique_corpus_identifier(add_text): """ Don't allow duplicate corpus+identifier. """ add_text(corpus='jstor', identifier='001') with pytest.raises(IntegrityError): add_text(corpus='jstor', identifier='001')
Example #28
Source File: report_model.py From openrasp-iast with Apache License 2.0 | 5 votes |
def put(self, request_data_list, plugin_name, description, message): """ 插入一条RaspResult数据 Parameters: rasp_result_instance - RaspResult实例,待插入的数据 plugin_name - str, 插件名 message - str, 漏洞描述 Returns: 插入成功返回True, 重复返回False Raises: exceptions.DatabaseError - 数据库错误引发此异常 """ try: rasp_result_json_list = [] for request_data in request_data_list: rasp_result_json_list.append(json.loads( request_data.get_rasp_result().dump())) payload_seq = request_data_list[0].get_payload_info()["seq"] data = { "plugin_name": plugin_name, "description": description, "rasp_result_list": json.dumps(rasp_result_json_list), "payload_seq": payload_seq, "message": message } await peewee_async.create_object(self.Report, **data) except peewee.IntegrityError: return False except asyncio.CancelledError as e: raise e except Exception as e: self._handle_exception("DB error in method put!", e) else: return True
Example #29
Source File: test_indexes.py From open-syllabus-project with Apache License 2.0 | 5 votes |
def test_unique_url(add_institution): """ URLs should be unique. """ add_institution(url='http://test.edu') with pytest.raises(peewee.IntegrityError): add_institution(url='http://test.edu')
Example #30
Source File: starboard.py From rowboat with MIT License | 4 votes |
def on_message_reaction_add(self, event): try: # Grab the message, and JOIN across blocks to check if a block exists # for either the message author or the reactor. msg = Message.select( Message, StarboardBlock ).join( StarboardBlock, join_type=JOIN.LEFT_OUTER, on=( ( (Message.author_id == StarboardBlock.user_id) | (StarboardBlock.user_id == event.user_id) ) & (Message.guild_id == StarboardBlock.guild_id) ) ).where( (Message.id == event.message_id) ).get() except Message.DoesNotExist: return # If either the reaction or message author is blocked, prevent this action if msg.starboardblock.user_id: event.delete() return # Check if the board prevents self stars sb_id, board = event.config.get_board(event.channel_id) if not sb_id: return if board.prevent_self_star and msg.author_id == event.user_id: event.delete() return try: StarboardEntry.add_star(event.message_id, event.user_id) except peewee.IntegrityError: msg = self.client.api.channels_messages_get( event.channel_id, event.message_id) if msg: Message.from_disco_message(msg) StarboardEntry.add_star(event.message_id, event.user_id) else: return self.queue_update(event.guild.id, event.config)