Python django.db 模块,IntegrityError() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.db.IntegrityError()

项目:TeleGiphy    作者:JessicaNgo    | 项目源码 | 文件源码
def new_game(request):
    """
    This view creates a new game token when a user clicks on "New Game" button on index.html
    This is done randomly and then checks in the database to see if that token is already present.
    If so, it'll keep on trying until it finds a unique token.
    """
    # Makes initial token
    new_token = str(random.randint(1000, 9999))
    # Checks to see if the token created is unique
    # What if ALL tokens already taken? Well, that would suck!
    while Game.objects.filter(token=new_token).exists():
        new_token = str(random.randint(1000, 9999))
    # Make new game in database with the token
    if 'game_mode' not in request.session:
        request.session['game_mode'] = request.POST['game_mode']
    game = Game(token=new_token, mode=request.session['game_mode'])
    game.save()
    if not request.user.is_authenticated():
        _give_random_name(request)

    try:
        _attach_user_to_game(game, request)
    except IntegrityError:
        return redirect(reverse('game:index'))
    return HttpResponseRedirect(reverse('game:pre_game_room', args=(new_token,)))
项目:django-codenerix-products    作者:centrologic    | 项目源码 | 文件源码
def form_valid(self, form):
        if self.__product_pk:
            product_final = ProductFinal.objects.get(pk=self.__product_pk)
            self.request.product_final = product_final
            form.instance.product_final = product_final

        try:
            return super(ProductUniqueCreate, self).form_valid(form)
        except ValidationError as e:
            errors = form._errors.setdefault("value", ErrorList())
            errors.append(e)
            return super(ProductUniqueCreate, self).form_invalid(form)
        except IntegrityError:
            errors = form._errors.setdefault("value", ErrorList())
            errors.append(_("Value existing"))
            return super(ProductUniqueCreate, self).form_invalid(form)
项目:django_pipedrive    作者:MasAval    | 项目源码 | 文件源码
def index(request):

    enable_hstore()

    try:
        if request.method == 'POST':

            json_data = json.loads(request.body)
            meta = json_data[u'meta']

            # API v1
            if meta[u'v'] == 1:
                return handle_v1(json_data)
            else:
                raise NonImplementedVersionException()

    except IntegrityError as e:
        logging.warning(e.message)
        logging.warning("Forcing full sync from pipedrive")
        PipedriveModel.sync_from_pipedrive()

    return HttpResponse("Hello, world!")
项目:django_pipedrive    作者:MasAval    | 项目源码 | 文件源码
def sync_one(cls, external_id, last_error=None):
        post_data = cls.pipedrive_api_client.get_instance(external_id)

        # Error code from the API
        if not post_data[u'success']:
            logging.error(post_data)
            raise UnableToSyncException(cls, external_id)
        try:
            return cls.update_or_create_entity_from_api_post(post_data[u'data'])
        except IntegrityError as e:
            logging.warning(e)
            if e.message == last_error:
                raise SameErrorTwiceSyncException(cls, external_id, e.message)
            match = re.search('.*Key \((.*)\)=\((.*)\).*', e.message)
            if match:
                field_name = match.group(1)
                field_id = match.group(2)
                model = cls.field_model_map(field_name)
                model.sync_one(field_id)
                return cls.sync_one(external_id, e.message)
            else:
                raise Exception("Could not handle error message")
项目:TeleGiphy    作者:JessicaNgo    | 项目源码 | 文件源码
def choose_name(request):
    username = request.POST['username']
    try:
        user = User.objects.create(username=username)
        if request.user.is_authenticated():
            old_user = request.user
            django_logout(request)
            old_user.delete()
        _login_user(request, user)
        messages.success(request, 'You have chosen "{}"!'.format(username))
    except IntegrityError:
        messages.error(request, 'Sorry, "{}" is already taken :('.format(username))

    return redirect(request.GET.get('next', '/'))


# Gets context of previous and current player actions for Hotseat Gameplay
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def save(self, must_create=False):
        """
        Saves the current session data to the database. If 'must_create' is
        True, a database error will be raised if the saving operation doesn't
        create a *new* entry (as opposed to possibly updating an existing
        entry).
        """
        if self.session_key is None:
            return self.create()
        data = self._get_session(no_load=must_create)
        obj = self.create_model_instance(data)
        using = router.db_for_write(self.model, instance=obj)
        try:
            with transaction.atomic(using=using):
                obj.save(force_insert=must_create, using=using)
        except IntegrityError:
            if must_create:
                raise CreateError
            raise
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
def save(self, must_create=False):
        """
        Saves the current session data to the database. If 'must_create' is
        True, a database error will be raised if the saving operation doesn't
        create a *new* entry (as opposed to possibly updating an existing
        entry).
        """
        if self.session_key is None:
            return self.create()
        data = self._get_session(no_load=must_create)
        obj = self.create_model_instance(data)
        using = router.db_for_write(self.model, instance=obj)
        try:
            with transaction.atomic(using=using):
                obj.save(force_insert=must_create, force_update=not must_create, using=using)
        except IntegrityError:
            if must_create:
                raise CreateError
            raise
        except DatabaseError:
            if not must_create:
                raise UpdateError
            raise
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def language_add_new(request, language_list):
    language_list = LanguageList.objects.get(name=language_list)
    if request.method == 'POST':
        form = AddLanguageForm(request.POST)
        if "cancel" in form.data:  # has to be tested before data is cleaned
            return HttpResponseRedirect(reverse("view-language-list",
                                                args=[language_list.name]))
        if form.is_valid():
            with transaction.atomic():
                form.save()
                language = Language.objects.get(
                    ascii_name=form.cleaned_data["ascii_name"])
                try:
                    language_list.append(language)
                except IntegrityError:
                    pass  # automatically inserted into LanguageList.DEFAULT
            return HttpResponseRedirect(reverse("language-edit",
                                                args=[language.ascii_name]))
    else:  # first visit
        form = AddLanguageForm()
    return render_template(request, "language_add_new.html",
                           {"form": form})
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def test_can_delete_penultimate_citation(self):
        # can't delete final citation without deleting CognateClass itself
        cognate_judgement = CognateJudgement.objects.create(
                lexeme=self.lexeme,
                cognate_class=self.cognate_class)
        citation_1 = CognateJudgementCitation.objects.create(
                source=self.source,
                cognate_judgement=cognate_judgement,
                reliability="B")
        citation_2 = CognateJudgementCitation.objects.create(
                source=Source.objects.create(citation_text="B"),
                cognate_judgement=cognate_judgement,
                reliability="X")
        self.assertEqual(cognate_judgement.source.count(), 2)
        citation_2.delete()
        self.assertEqual(cognate_judgement.source.count(), 1)
        self.assertRaises(IntegrityError, self.delete, citation_1)
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def test_can_delete_penultimate_citation(self):
        lexeme = Lexeme.objects.create(
            romanised="a",
            meaning=self.meaning,
            language=self.language)
        citation_1 = LexemeCitation.objects.create(
                lexeme=lexeme,
                source=self.source,
                reliability="B")
        citation_2 = LexemeCitation.objects.create(
                lexeme=lexeme,
                source=Source.objects.create(citation_text="B"),
                reliability="X")
        self.assertEqual(lexeme.source.count(), 2)
        citation_2.delete()
        self.assertEqual(lexeme.source.count(), 1)
        self.assertRaises(IntegrityError, self.delete, citation_1)
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
def test_can_still_delete_on_cascade(self):
        lexeme = Lexeme.objects.create(
                romanised="a",
                meaning=self.meaning,
                language=self.language)
        citation = LexemeCitation.objects.create(
                lexeme=lexeme,
                source=self.source,
                reliability="B")
        # sanity check
        self.assertRaises(IntegrityError, self.delete, citation)
        self.assertEqual(Lexeme.objects.count(), 1)
        self.assertEqual(LexemeCitation.objects.count(), 1)
        # delete tests
        try:
            lexeme.delete()
        except IntegrityError:
            self.fail("Should be able to delete final citation via cascade")
        self.assertEqual(Lexeme.objects.count(), 0)
        self.assertEqual(LexemeCitation.objects.count(), 0)
项目:Server    作者:malaonline    | 项目源码 | 文件源码
def approve_withdraw(self, request, ahid):
        ok = False
        try:
            with transaction.atomic():
                ah = models.AccountHistory.objects.get(id=ahid)
                if not ah.withdrawal.is_pending():
                    return JsonResponse({'ok': False, 'msg': '???????', 'code': -1})
                ah.audit_withdrawal(True, request.user)
                ok = True
        except IntegrityError as err:
            logger.error(err)
            return JsonResponse({'ok': False, 'msg': '????, ???????????', 'code': -1})
        if ok:
            # ??????
            teacher = ah.account.user.teacher
            _try_send_sms(teacher.user.profile.phone, smsUtil.TPL_WITHDRAW_APPROVE, {'username':teacher.name}, 2)
        return JsonResponse({'ok': True, 'msg': 'OK', 'code': 0})
项目:Server    作者:malaonline    | 项目源码 | 文件源码
def post(self, request, *args, **kwargs):
        tsid = kwargs.get('tsid')
        gids = request.POST.get('gids')
        gid_list = gids and gids.split(',') or []
        lcts = get_object_or_404(models.LiveCourseTimeSlot, pk=tsid)
        try:
            with transaction.atomic():
                lcts.question_groups.clear()
                if gid_list:
                    for g in models.QuestionGroup.objects.filter(
                            id__in=gid_list, deleted=False):
                        lcts.question_groups.add(g)
                lcts.save()
        except IntegrityError as err:
            logger.error(err)
            return JsonResponse(
                {'ok': False, 'msg': '????, ???????????', 'code': -1})
        return JsonResponse({'ok': True, 'msg': 'OK', 'code': 0})
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
def save(self, must_create=False):
        """
        Saves the current session data to the database. If 'must_create' is
        True, a database error will be raised if the saving operation doesn't
        create a *new* entry (as opposed to possibly updating an existing
        entry).
        """
        if self.session_key is None:
            return self.create()
        data = self._get_session(no_load=must_create)
        obj = self.create_model_instance(data)
        using = router.db_for_write(self.model, instance=obj)
        try:
            with transaction.atomic(using=using):
                obj.save(force_insert=must_create, force_update=not must_create, using=using)
        except IntegrityError:
            if must_create:
                raise CreateError
            raise
        except DatabaseError:
            if not must_create:
                raise UpdateError
            raise
项目:lighthouse    作者:dstl    | 项目源码 | 文件源码
def post(self, request, *args, **kwargs):

        #   If we are not logged in, send the user to the login page
        if not self.request.user.is_authenticated():
            return redirect(reverse('home'))

        #   Grab the id of the user and team we are attempting to join
        team_id = kwargs.get('pk')

        #   Make sure the team exists, and that we haven't been lied
        #   to with the URL
        team = Team.objects.filter(pk=team_id)
        check_team = team.exists()
        if check_team is False:
            return redirect(reverse('team-list'))

        #   Try and add the team to the user
        try:
            request.user.teams.add(team_id)
        except IntegrityError:
            return redirect(reverse('team-detail', kwargs={'pk': team_id}))

        return redirect(reverse('team-detail', kwargs={'pk': team_id}))
项目:lighthouse    作者:dstl    | 项目源码 | 文件源码
def post(self, request, *args, **kwargs):

        #   If we are not logged in, send the user to the login page
        if not self.request.user.is_authenticated():
            return redirect(reverse('home'))

        #   Grab the id of the user and team we are attempting to join
        team_id = kwargs.get('pk')

        #   Make sure the team exists, and that we haven't been lied
        #   to with the URL
        team = Team.objects.filter(pk=team_id)
        check_team = team.exists()
        if check_team is False:
            return redirect(reverse('team-list'))

        #   Try and remove the team to the user
        try:
            request.user.teams.remove(team_id)
        except IntegrityError:
            return redirect(reverse('team-detail', kwargs={'pk': team_id}))

        return redirect(reverse('team-detail', kwargs={'pk': team_id}))
项目:django-example    作者:gen1us2k    | 项目源码 | 文件源码
def update_balance(self, reason, money, **kwargs):
        from billing.models import MoneyLog
        ml_filter = {}
        task = kwargs.get('task', None)
        ml_filter['reason'] = reason
        ml_filter['user'] = self
        ml_filter['debit'] = math.fabs(money) if money < 0 else 0
        ml_filter['credit'] = math.fabs(money) if money > 0 else 0
        ml_filter['money'] = money
        ml_filter['task'] = task
        current_balance = User.objects.select_for_update().get(pk=self.pk).balance
        ml_filter['balance'] = current_balance + Decimal(money)

        try:
            ml = MoneyLog.objects.get(**ml_filter)
        except MoneyLog.DoesNotExist:
            try:
                ml = MoneyLog.objects.create(**ml_filter)
            except IntegrityError:
                ml = MoneyLog.objects.get(**ml_filter)

            # User.objects.select_for_update().filter(pk=self.pk).update(
            #     balance=F('balance') + Decimal(money)
            # )
项目:dixit-online    作者:jminuscula    | 项目源码 | 文件源码
def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if not serializer.is_valid():
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

        try:
            game = self.get_game()
            player = game.add_player(request.user, request.data['name'])
        except IntegrityError as exc:
            if 'user_id' in str(exc):
                return Response({"detail": 'You are already playing this game'},
                                status=status.HTTP_403_FORBIDDEN)
            return Response({"detail": "Username already in use"}, status=status.HTTP_403_FORBIDDEN)

        data = PlayerSerializer(player).data
        return Response(data, status=status.HTTP_201_CREATED)
项目:lti-demo-haiku    作者:open-craft    | 项目源码 | 文件源码
def authentication_hook(self, request, user_id=None, username=None, email=None, extra_params=None):
        extra = extra_params if extra_params else {}

        # automatically generate password from user_id
        password = self._generate_password(user_id, settings.PASSWORD_GENERATOR_NONCE)

        # username and email might be empty, depending on how edX LTI module is configured:
        # there are individual settings for that + if it's embedded into an iframe it never sends
        # email and username in any case
        # so, since we want to track user for both iframe and non-iframe LTI blocks, username is completely ignored
        uname = self._compress_user_name(user_id)
        email = email if email else user_id+'@localhost'
        try:
            User.objects.get(username=uname)
        except User.DoesNotExist:
            try:
                User.objects.create_user(username=uname, email=email, password=password)
            except IntegrityError as e:
                # A result of race condition of multiple simultaneous LTI requests - should be safe to ignore,
                # as password and uname are stable (i.e. not change for the same user)
                logger.info("IntegrityError creating user - assuming result of race condition: %s", e.message)

        authenticated = authenticate(username=uname, password=password)
        login(request, authenticated)
项目:registration    作者:HackAssistant    | 项目源码 | 文件源码
def post(self, request, *args, **kwargs):
        tech_vote = request.POST.get('tech_rat', None)
        pers_vote = request.POST.get('pers_rat', None)
        comment_text = request.POST.get('comment_text', None)
        application = models.Application.objects.get(pk=request.POST.get('app_id'))
        try:
            if request.POST.get('skip'):
                add_vote(application, request.user, None, None)
            elif request.POST.get('add_comment'):
                add_comment(application, request.user, comment_text)
            else:
                add_vote(application, request.user, tech_vote, pers_vote)
        # If application has already been voted -> Skip and bring next
        # application
        except IntegrityError:
            pass
        return HttpResponseRedirect(reverse('review'))
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def create(body):
    """ Create new tag
    """
    try:
        body.pop('id', None)
        if body.get('tagType') not in TAG_TYPE:
            raise BadRequest('Invalid or missing tag type')

        existing = [tag.lower() for tag in Tag.objects.all().values_list('name', flat=True)]
        if body['name'].lower().strip() in existing:
            raise BadRequest('Tag already exists')
        body['codename'] = body['name'].lower().replace(' ', '_')
        tag = Tag.objects.get_or_create(**body)[0]
    except (AttributeError, KeyError, FieldError, IntegrityError, ValueError):
        raise BadRequest('Invalid fields in body')
    return model_to_dict(tag)
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def update(tag_id, body):
    """ Update category
    """
    try:
        tag = Tag.objects.get(id=tag_id)
    except (ObjectDoesNotExist, ValueError):
        raise NotFound('Tag not found')
    try:
        body.pop('id', None)

        existing = Tag.objects.exclude(id=tag.id).values_list('name', flat=True)
        existing = [tg.lower() for tg in existing]
        if body['name'].lower().strip() in existing:
            raise BadRequest('Tag already exists')

        Tag.objects.filter(pk=tag.pk).update(**body)
        tag = Tag.objects.get(pk=tag.pk)
    except (AttributeError, KeyError, FieldError, IntegrityError, ValueError, TypeError):
        raise BadRequest('Invalid fields in body')
    return model_to_dict(tag)
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def _update_duration(ticket, data, user):
    """ Generic update for duration
    """
    try:
        key = data.keys()[0]
        previous = getattr(ticket, key)
        data[key.replace('Duration', 'Start')] = datetime.now()

        Ticket.objects.filter(pk=ticket.pk).update(**data)
        ticket = Ticket.objects.get(pk=ticket.pk)

        database.log_action_on_ticket(
            ticket=ticket,
            action='update_property',
            user=user,
            property=key.replace('Duration', ''),
            previous_value=str(timedelta(seconds=previous)),
            new_value=str(timedelta(seconds=getattr(ticket, key)))
        )

    except (FieldDoesNotExist, FieldError, IntegrityError, TypeError, ValueError) as ex:
        raise BadRequest(str(ex.message))

    return show(ticket.id, user)
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def update_proof(ticket_id, proof_id, body, user):
    """ Update proof
    """
    ticket = None
    try:
        ticket = Ticket.objects.get(id=ticket_id)
        Proof.objects.get(id=proof_id)
    except (ObjectDoesNotExist, ValueError):
        raise NotFound('Not Found')

    try:
        body.pop('id', None)
        body.pop('ticket', None)
        ticket.proof.update(**body)
        ticket.save()
        database.log_action_on_ticket(
            ticket=ticket,
            action='update_proof',
            user=user
        )
    except (KeyError, FieldDoesNotExist, FieldError, IntegrityError, TypeError, ValueError) as ex:
        raise BadRequest(str(ex.message))
    return {'message': 'Proof successfully updated'}
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def delete_proof(ticket_id, proof_id, user):
    """ Delete proof
    """
    try:
        ticket = Ticket.objects.get(id=ticket_id)
    except (ObjectDoesNotExist, ValueError):
        raise NotFound('Ticket not found')

    try:
        proof = ticket.proof.get(id=proof_id)
        proof.delete()
        database.log_action_on_ticket(
            ticket=ticket,
            action='delete_proof',
            user=user
        )
    except (ObjectDoesNotExist, KeyError, FieldDoesNotExist,
            FieldError, IntegrityError, TypeError, ValueError) as ex:
        raise BadRequest(str(ex.message))
    return {'message': 'Proof successfully deleted'}
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def add_tag(ticket_id, body, user):
    """ Add ticket tag
    """
    try:
        tag = Tag.objects.get(**body)
        ticket = Ticket.objects.get(id=ticket_id)

        if ticket.__class__.__name__ != tag.tagType:
            raise BadRequest('Invalid tag for ticket')

        ticket.tags.add(tag)
        ticket.save()
        database.log_action_on_ticket(
            ticket=ticket,
            action='add_tag',
            user=user,
            tag_name=tag.name
        )
    except MultipleObjectsReturned:
        raise BadRequest('Please use tag id')
    except (KeyError, FieldError, IntegrityError, ObjectDoesNotExist, ValueError):
        raise NotFound('Tag or ticket not found')
    return {'message': 'Tag successfully added'}
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def update(news_id, body, user):
    """ Update news
    """
    try:
        if user.is_superuser:
            news = News.objects.get(id=news_id)
        else:
            news = News.objects.get(id=news_id, author__id=user.id)
    except (ObjectDoesNotExist, ValueError):
        return NotFound('News not found')
    try:
        body = {k: v for k, v in body.iteritems() if k not in ['author', 'date', 'tags']}
        News.objects.filter(pk=news.pk).update(**body)
        news = News.objects.get(pk=news.pk)
    except (KeyError, FieldError, IntegrityError):
        raise BadRequest('Invalid fields in body')
    return model_to_dict(news)
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def create(body, user):
    """
        Create a new report item
    """
    try:
        resp = __get_item_infos(body, user)
        item, created = ReportItem.objects.get_or_create(**resp)
        if resp['report'].ticket:
            database.log_action_on_ticket(
                ticket=resp['report'].ticket,
                action='add_item',
                user=user
            )
    except (AttributeError, FieldError, IntegrityError, KeyError, ObjectDoesNotExist) as ex:
        raise BadRequest(str(ex.message))
    if not created:
        raise BadRequest('Report items already exists')
    return show(item.id)
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def update(item_id, body, user):
    """
        Update a report item
    """
    try:
        item = ReportItem.objects.get(id=item_id)
    except (ObjectDoesNotExist, ValueError):
        raise NotFound('Item not found')

    try:
        resp = __get_item_infos(body, user)
        ReportItem.objects.filter(pk=item.pk).update(**resp)
        item = ReportItem.objects.get(pk=item.pk)
        if resp['report'].ticket:
            database.log_action_on_ticket(
                ticket=resp['report'].ticket,
                action='update_item',
                user=user
            )
    except (AttributeError, FieldError, IntegrityError, KeyError, ObjectDoesNotExist):
        raise BadRequest('Invalid fields in body')
    return show(item_id)
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def remove_tag(defendant_id, tag_id, user):
    """ Remove defendant tag
    """
    try:
        tag = Tag.objects.get(id=tag_id)
        defendant = Defendant.objects.get(id=defendant_id)

        for defendt in Defendant.objects.filter(customerId=defendant.customerId):
            defendt.tags.remove(tag)
            defendt.save()

            for ticket in defendt.ticketDefendant.all():
                database.log_action_on_ticket(
                    ticket=ticket,
                    action='remove_tag',
                    user=user,
                    tag_name=tag.name
                )

    except (ObjectDoesNotExist, FieldError, IntegrityError, ValueError):
        raise NotFound('Defendant or tag not found')

    return show(defendant_id)
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def update(prov, body):
    """ Update provider infos
    """
    try:
        provider = Provider.objects.get(email=prov)
    except (ObjectDoesNotExist, ValueError):
        raise NotFound('Provider does not exist')
    try:
        body = {k: v for k, v in body.iteritems() if k in PROVIDER_FIELDS}
        cat = None
        if body.get('defaultCategory'):
            cat = Category.objects.get(name=body['defaultCategory'])
        body.pop('defaultCategory', None)
        Provider.objects.filter(pk=provider.pk).update(defaultCategory=cat, **body)
        provider = Provider.objects.get(pk=provider.pk)
    except (FieldError, IntegrityError, ObjectDoesNotExist) as ex:
        raise BadRequest(str(ex.message))
    return model_to_dict(provider)
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def add_tag(provider_email, body):
    """ Add provider tag
    """
    try:
        tag = Tag.objects.get(**body)
        provider = Provider.objects.get(email=provider_email)

        if provider.__class__.__name__ != tag.tagType:
            raise BadRequest('Invalid tag for provider')

        provider.tags.add(tag)
        provider.save()

    except (KeyError, FieldError, IntegrityError, ObjectDoesNotExist, ValueError):
        raise NotFound('Provider or tag not found')
    return model_to_dict(provider)
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def remove_tag(provider_email, tag_id):
    """ Remove defendant tag
    """
    try:
        tag = Tag.objects.get(id=tag_id)
        provider = Provider.objects.get(email=provider_email)

        if provider.__class__.__name__ != tag.tagType:
            raise BadRequest('Invalid tag for provider')

        provider.tags.remove(tag)
        provider.save()

    except (ObjectDoesNotExist, FieldError, IntegrityError, ValueError):
        raise NotFound('Provider or tag not found')
    return model_to_dict(provider)
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def add_tag(report_id, body):
    """ Add report tag
    """
    try:
        tag = Tag.objects.get(**body)
        report = Report.objects.get(id=report_id)

        if report.__class__.__name__ != tag.tagType:
            raise BadRequest('Invalid tag for report')

        report.tags.add(tag)
        report.save()
    except MultipleObjectsReturned:
        raise BadRequest('Please use tag id')
    except (KeyError, FieldError, IntegrityError, ObjectDoesNotExist, ValueError):
        raise NotFound('Report or tag not found')
    return {'message': 'Tag successfully added'}
项目:shiva-dropped    作者:sansaralab    | 项目源码 | 文件源码
def handle_background(caller_type, person_id, caller_name, caller_value):
    from .services import get_or_create_person
    from .handlers import handle_backend_event

    caller_type = int(caller_type)
    person = get_or_create_person(person_id)

    if caller_type == ACTION_TYPES['EVENT']:
        PersonEvent.objects.create(person=person, event_name=caller_name, event_value=caller_value)
    elif caller_type == ACTION_TYPES['CONTACT']:
        try:
            PersonContact.objects.create(person=person, contact_type=caller_name, contact_value=caller_value)
        except IntegrityError:
            pass
    elif caller_type == ACTION_TYPES['DATA']:
        try:
            PersonData.objects.create(person=person, data_type=caller_name, data_value=caller_value)
        except IntegrityError:
            pass
    else:
        print("some error")

    return handle_backend_event(caller_type, person_id, caller_name, caller_value)
项目:django    作者:alexsukhrin    | 项目源码 | 文件源码
def save(self, must_create=False):
        """
        Saves the current session data to the database. If 'must_create' is
        True, a database error will be raised if the saving operation doesn't
        create a *new* entry (as opposed to possibly updating an existing
        entry).
        """
        if self.session_key is None:
            return self.create()
        data = self._get_session(no_load=must_create)
        obj = self.create_model_instance(data)
        using = router.db_for_write(self.model, instance=obj)
        try:
            with transaction.atomic(using=using):
                obj.save(force_insert=must_create, force_update=not must_create, using=using)
        except IntegrityError:
            if must_create:
                raise CreateError
            raise
        except DatabaseError:
            if not must_create:
                raise UpdateError
            raise
项目:django-eventstream    作者:fanout    | 项目源码 | 文件源码
def messages(request, room_id):
    if request.method == 'POST':
        try:
            room = ChatRoom.objects.get(eid=room_id)
        except ChatRoom.DoesNotExist:
            try:
                room = ChatRoom(eid=room_id)
                room.save()
            except IntegrityError:
                # someone else made the room. no problem
                room = ChatRoom.objects.get(eid=room_id)

        mfrom = request.POST['from']
        text = request.POST['text']
        with transaction.atomic():
            msg = ChatMessage(room=room, user=mfrom, text=text)
            msg.save()
            send_event('room-%s' % room_id, 'message', msg.to_data())
        body = json.dumps(msg.to_data(), cls=DjangoJSONEncoder)
        return HttpResponse(body, content_type='application/json')
    else:
        return HttpResponseNotAllowed(['POST'])
项目:Quantrade    作者:quant-trade    | 项目源码 | 文件源码
def write_stats(stats, broker, symbol, period, system, direction):
    try:
        if stats['trades'] >= settings.MIN_TRADES:
            try:
                s = Stats.objects.create(broker=broker, symbol=symbol, period=period, \
                    system=system, direction=direction, sharpe=stats['sharpe'], \
                    std=stats['std'], var=stats['var'], avg_trade=stats['avg_trade'], \
                    avg_win=stats['avg_win'], avg_loss=stats['avg_loss'], \
                    win_rate=stats['win_rate'], trades=stats['trades'], fitness=stats['fr'], \
                    intraday_dd=stats['intraday_dd'], max_dd=stats['max_dd'], \
                    total_profit=stats['total_profit'], yearly=stats['yearly'], yearly_p=stats['avg_yearly_p'], \
                    acc_minimum=stats['acc_minimum'], bh_sharpe=stats['bh_sharpe'], \
                    sortino=stats['sortino'], bh_sortino=stats['bh_sortino'])
                s.save()
                print(colored.green("Wrote new stats for {}".format(symbol)))
            except IntegrityError:
                pass
            except Exception as e:
                print(colored.red("At write_stats {}".format(e)))
                await update_stats(broker=broker, symbol=symbol, period=period, \
                    system=system, direction=direction, stats=stats)
    except Exception as err:
        print(colored.red("At writing stats {}".format(err)))
项目:teamreporter    作者:agilentia    | 项目源码 | 文件源码
def post(self, request, *args, **kwargs):
        user = request.user
        team_info = json.loads(request.body.decode("utf-8"))
        validator = Validator(team_schema)
        if not validator.validate(team_info):
            return JsonResponse({'error': validator.errors})
        survey_send_time = parser.parse(team_info['send_time']).replace(second=0, microsecond=0)
        summary_send_time = parser.parse(team_info['summary_time']).replace(second=0, microsecond=0)
        rule = recurrence.Rule(recurrence.WEEKLY, byday=team_info['days_of_week'])
        now = datetime.datetime.now()
        exdates = []
        if survey_send_time < now:
            exdates.append(now.replace(hour=0, minute=0, second=0, microsecond=0))
        rec = recurrence.Recurrence(rrules=[rule], exdates=exdates)

        try:
            team = Team.objects.create(admin=user, name=team_info['name'])
        except IntegrityError:
            return JsonResponse({'error': {"name": _("team with this name already exists")}})
        Report.objects.create(team=team, recurrences=rec, survey_send_time=survey_send_time,
                              summary_send_time=summary_send_time)
        team_dict = model_to_dict(team, exclude=['users'])
        team_dict['report'] = self.report_dict(team)
        return JsonResponse({'team': team_dict})
项目:teamreporter    作者:agilentia    | 项目源码 | 文件源码
def post(self, request, *args, **kwargs):
        team_id = int(self.kwargs['team_id'])
        team = get_object_or_404(Team, pk=team_id)
        check_scope(request, team)

        user_info = json.loads(request.body.decode('utf-8'))
        validator = Validator(user_schema)
        if not validator.validate(user_info):
            return JsonResponse({'error': validator.errors})

        role_ids = [role['id'] for role in user_info['roles']]
        defaults = {k: user_info[k] for k in ['first_name', 'last_name', 'email']}
        defaults['username'] = hashlib.md5(user_info['email'].encode('utf-8')).hexdigest()[:30]
        user, created = User.objects.get_or_create(email=user_info['email'], defaults=defaults)

        try:
            membership = Membership.objects.create(team=team, user=user)
            membership.roles.add(*role_ids)
            membership.save()
        except IntegrityError:
            return JsonResponse({'error': {"name": _("user already part of the team")}})
        user_dict = model_to_dict(user, fields=['email', 'first_name', 'last_name', 'id'])
        user_dict['roles'] = user_info['roles']
        return JsonResponse({'user': user_dict})
项目:django-mpathy    作者:craigds    | 项目源码 | 文件源码
def test_move_root_with_children_to_nonroot(db):
    a = MyTree.objects.create(label='a')
    b = MyTree.objects.create(label='b')
    c = MyTree.objects.create(label='c', parent=b)
    MyTree.objects.move_subtree(b, a)
    assert b.parent.label == 'a'
    assert b.ltree == 'a.b'
    assert set(a.get_children()) == {b}
    assert set(b.get_children()) == {c}

    flush_constraints()
    with pytest.raises(IntegrityError):
        # This node no longer has a valid ltree path, it was re-written in
        # the database when we moved b.
        # So we check that saving it with the old path correctly raises an error.
        c.save()
        flush_constraints()
项目:django-konfera    作者:pyconsk    | 项目源码 | 文件源码
def test_slug(self):
        title_length = Event._meta.get_field('title').max_length
        slug_length = Event._meta.get_field('slug').max_length
        self.assertGreaterEqual(slug_length, title_length)

        title = random_string(title_length)
        slug = slugify(title)
        date_from = now
        date_to = date_from + datetime.timedelta(seconds=1)
        location = models.Location.objects.order_by('?').first()
        event1 = Event(title=title, slug=slug, event_type=Event.MEETUP, date_from=date_from, date_to=date_to,
                       location=location, cfp_allowed=False)
        event1.save()
        self.assertEqual(Event.objects.get(slug=slug).title, title)

        event2 = Event(title=random_string(128, unicode=True), slug=slug, event_type=Event.MEETUP, date_from=date_from,
                       date_to=date_to, location=location, cfp_allowed=False)
        self.assertRaises(IntegrityError, event2.save)  # slug must be unique
项目:autoreg    作者:pbeyssac    | 项目源码 | 文件源码
def rq_run(out):
  import autoreg.dns.db
  dd = autoreg.dns.db.db(dbc=connection.cursor())
  dd.login('autoreg')
  whoisdb = autoreg.whois.db.Main(dbc=connection.cursor())

  rl = Requests.objects.exclude(pending_state=None).order_by('id')

  for r in rl:
    with transaction.atomic():
      r2 = Requests.objects.select_for_update().get(id=r.id)
      try:
        r2.do_pending_exc(out, dd, whoisdb)
        ok = True
      except IntegrityError as e:
        print(six.text_type(e), file=out)
        ok = False
      if ok:
        print(_("Status: committed"), file=out)
      else:
        print(_("Status: cancelled"), file=out)
项目:QProb    作者:quant-trade    | 项目源码 | 文件源码
def save_tweet(entry, source):
    try:
        if settings.SHOW_DEBUG:
            print("Twitter handle {}".format(entry.user.screen_name))
        source_obj = await get_source_obj(source=source)
        if not source_obj is None:
            twit_obj = Twits.objects.create(tweet_id=entry.id, content=entry.text, \
                twitter_handle=source_obj, screen_name=entry.user.name, \
                profile_image=entry.user.profile_image_url, hashtags=entry.hashtags, \
                date=await twitter_date(entry.created_at))
            twit_obj.save()
            if settings.SHOW_DEBUG:
                print(colored.green("Tweet cached to db."))
    except IntegrityError:
        pass
    except Exception as err:
        print(colored.red("At save_tweet {}").format(err))
项目:QProb    作者:quant-trade    | 项目源码 | 文件源码
def save_tags(tags, entry):
    try:
        if len(tags) > 0:
            for tag in tags:
                if "'s" not in tag:
                    try:
                        tag_obj = Tags.objects.get(title=tag)
                    except ObjectDoesNotExist:
                        tag_obj = Tags.objects.create(title=tag)
                        tag_obj.save()
                        print(colored.green("Added tag '{0}' to entry".format(tag)))
                    entry.tags.add(tag_obj)
    except IntegrityError:
        pass
    except Exception as err:
        print(colored.red("At save_tags {}".format(err)))

    return entry
项目:QProb    作者:quant-trade    | 项目源码 | 文件源码
def remake_summaries_from_content():
    articles = Post.objects.filter(parsed=True)

    for article in articles:
        entry = Post.objects.get(title=article.title)

        try:
            print((colored.green("Got this entry: {0}".format(entry.title))))
            entry.summary = summarizer(data=entry.content, sentences=settings.SUMMARIZER_SENTENCES)
            entry.sentiment = sentiment(entry.content)
            entry.save()
            print(colored.green("Remade summary: {0}".format(entry.summary)))
        except IntegrityError:
            pass
        except Exception as err:
            print(colored.red("[ERROR] At remake summaries: {0}".format(err)))
项目:QProb    作者:quant-trade    | 项目源码 | 文件源码
def get_article(link_, original_link):
    try:
        if not ('page' in link_):
            article = get_body_from_internet(link_)
            if 'Definition' in article.title:
                entry = Terms.objects.create(term=article.title, text=article.text, \
                        movies=article.movies, image=article.top_image)
                entry.save()
                print("Article saved in db.")
                update_link(original_link, 'A')
            else:
                update_link(original_link, 'A')
        else:
            update_link(original_link, 'A')
    except IntegrityError as e:
        print(e)
        update_link(original_link, 'A')
项目:graphene-jwt-auth    作者:darwin4031    | 项目源码 | 文件源码
def jwt_blacklist_set_handler(payload):
    """
    Default implementation that blacklists a jwt token.
    Should return a black listed token or None.
    """
    try:
        data = {
            'jti': payload.get('jti'),
            'created': now(),
            'expires': datetime.fromtimestamp(payload.get('exp'), tz=utc)
        }
        token = JWTBlacklistToken.objects.create(**data)
    except (TypeError, IntegrityError, Exception):
        return None
    else:
        return token
项目:Gypsy    作者:benticarlos    | 项目源码 | 文件源码
def save(self, must_create=False):
        """
        Saves the current session data to the database. If 'must_create' is
        True, a database error will be raised if the saving operation doesn't
        create a *new* entry (as opposed to possibly updating an existing
        entry).
        """
        if self.session_key is None:
            return self.create()
        data = self._get_session(no_load=must_create)
        obj = self.create_model_instance(data)
        using = router.db_for_write(self.model, instance=obj)
        try:
            with transaction.atomic(using=using):
                obj.save(force_insert=must_create, force_update=not must_create, using=using)
        except IntegrityError:
            if must_create:
                raise CreateError
            raise
        except DatabaseError:
            if not must_create:
                raise UpdateError
            raise
项目:varapp-backend-py    作者:varapp    | 项目源码 | 文件源码
def add_new_db(path, dbname=None, sha=None, parent_db_id=None):
    """Add a new db found on disk at *path* to both settings and VariantsDb.
    :param sha: hash of the new db.
    """
    assert os.path.exists(path)
    filename = os.path.basename(path)
    dirname = os.path.dirname(path)
    dbname = dbname or db_name_from_filename(filename)
    size = os.path.getsize(path)
    logger.info("(+) Adding '{}' as '{}' to settings and users_db".format(path, dbname))
    add_db_to_settings(dbname, filename)
    try:
        newdb,created = VariantsDb.objects.get_or_create(
            name=dbname, filename=filename, location=dirname, is_active=1,
            hash=sha, size=size, visible_name=dbname, parent_db_id=parent_db_id)
        return newdb
    except IntegrityError:
        # Another process trying to create a similar entry with same filename and same hash
        # should not be allowed
        return