django.utils.translation.ugettext - python examples

Here are the examples of the python api django.utils.translation.ugettext taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

94 Examples 7

3 View Complete Implementation : test_forms.py
Copyright Apache License 2.0
Author : edisonlz
    def test_flatpage_nosites(self):
        data = dict(url='/myflatpage1/', **self.form_data)
        data.update({'sites': ''})

        f = FlatpageForm(data=data)

        self.astertFalse(f.is_valid())

        self.astertEqual(
            f.errors,
            {'sites': [translation.ugettext('This field is required.')]})

3 View Complete Implementation : models.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : jsmesami
    @property
    def formatted_text(self):
        text = ugettext(self.text)
        if self.system:
            if self.context:
                try:
                    text = format_html(text, **self.context)
                except KeyError:
                    past
            else:
                text = mark_safe(text)

        return format_html(
            '<span clast="date">{date}</span> {text}',
            date=date_format(self.created, 'SHORT_DATE_FORMAT', use_l10n=True),
            text=text,
        )

3 View Complete Implementation : forms.py
Copyright MIT License
Author : bpgc-cte
    def get_context(self, name, value, attrs):
        context = super(ReadOnlyPastwordHashWidget, self).get_context(name, value, attrs)
        summary = []
        if not value or value.startswith(UNUSABLE_PastWORD_PREFIX):
            summary.append({'label': ugettext("No pastword set.")})
        else:
            try:
                hasher = identify_hasher(value)
            except ValueError:
                summary.append({'label': ugettext("Invalid pastword format or unknown hashing algorithm.")})
            else:
                for key, value_ in hasher.safe_summary(value).items():
                    summary.append({'label': ugettext(key), 'value': value_})
        context['summary'] = summary
        return context

3 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : edisonlz
    def clean_comment(self):
        """
        If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn't
        contain anything in PROFANITIES_LIST.
        """
        comment = self.cleaned_data["comment"]
        if settings.COMMENTS_ALLOW_PROFANITIES == False:
            bad_words = [w for w in settings.PROFANITIES_LIST if w in comment.lower()]
            if bad_words:
                raise forms.ValidationError(ungettext(
                    "Watch your mouth! The word %s is not allowed here.",
                    "Watch your mouth! The words %s are not allowed here.",
                    len(bad_words)) % get_text_list(
                        ['"%s%s%s"' % (i[0], '-'*(len(i)-2), i[-1])
                         for i in bad_words], ugettext('and')))
        return comment

3 View Complete Implementation : organization_member_settings.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : NetEaseGame
    def resend_invite(self, request, organization, member):
        messages.success(request, ugettext('An invitation to join %(organization)s has been sent to %(email)s') % {
            'organization': organization.name,
            'email': member.email,
        })

        member.send_invite_email()

        redirect = reverse('sentry-organization-member-settings',
                           args=[organization.slug, member.id])

        return self.redirect(redirect)

3 View Complete Implementation : helpers.py
Copyright MIT License
Author : bpgc-cte
    def inline_formset_data(self):
        verbose_name = self.opts.verbose_name
        return json.dumps({
            'name': '#%s' % self.formset.prefix,
            'options': {
                'prefix': self.formset.prefix,
                'addText': ugettext('Add another %(verbose_name)s') % {
                    'verbose_name': capfirst(verbose_name),
                },
                'deleteText': ugettext('Remove'),
            }
        })

3 View Complete Implementation : views.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : jsmesami
@login_required
@_editor
def edit(request, fruit):
    form = FruitForm(request.POST or None, instance=fruit)

    if form.is_valid():
        form.save()
        messages.success(request, ugettext('Thank you, your changes have been saved.'))
        return redirect(fruit)

    context = {
        'kinds': Kind.objects.valid(),
        'fruit': fruit,
        'form': form,
    }

    return render(request, 'fruit/edit.html', context)

3 View Complete Implementation : models.py
Copyright Apache License 2.0
Author : BeanWei
    def __str__(self):
        if self.action_flag == 'create':
            return ugettext('Added "%(object)s".') % {'object': self.object_repr}
        elif self.action_flag == 'change':
            return ugettext('Changed "%(object)s" - %(changes)s') % {
                'object': self.object_repr,
                'changes': self.message,
            }
        elif self.action_flag == 'delete' and self.object_repr:
            return ugettext('Deleted "%(object)s."') % {'object': self.object_repr}

        return self.message

3 View Complete Implementation : search.py
Copyright MIT License
Author : meine-stadt-transparent
def _add_date_after(search, params, options, errors):
    """ Filters by a date given a string, catching parsing errors. """
    try:
        after = parse(params["after"])
    except (ValueError, OverflowError) as e:
        errors.append(
            ugettext(
                "The value for after is invalid. The correct format is YYYY-MM-DD or YYYY-MM-DD HH:MM:SS: "
                + str(e)
            )
        )
        return search
    search = search.filter(
        Q("range", start={"gte": after}) | Q("range", legal_date={"gte": after})
    )
    options["after"] = after
    return search

3 View Complete Implementation : models.py
Copyright Apache License 2.0
Author : drexly
    def __str__(self):
        if self.is_addition():
            return ugettext('Added "%(object)s".') % {'object': self.object_repr}
        elif self.is_change():
            return ugettext('Changed "%(object)s" - %(changes)s') % {
                'object': self.object_repr,
                'changes': self.change_message,
            }
        elif self.is_deletion():
            return ugettext('Deleted "%(object)s."') % {'object': self.object_repr}

        return ugettext('LogEntry Object')

3 View Complete Implementation : resolvers.py
Copyright MIT License
Author : ulule
def location(request):
    """
    Transform an IP address into an approximate location.
    """
    ip = utils.resolve(app_settings.IP_RESOLVER, request)

    try:
        location = GeoIP() and GeoIP().city(ip)
    except:
        # Handle 127.0.0.1 and not found IPs
        return ugettext('unknown')

    if location and location['country_name']:
        if location['city']:
            return '%s, %s' % (location['city'], location['country_name'])
        else:
            return location['country_name']

    return ugettext('unknown')

3 View Complete Implementation : forms.py
Copyright MIT License
Author : PacktPublishing
    def save(self):
        cleaned_data = self.cleaned_data
        send_mail(
            subject=ugettext("A message from %s") % self.request.user,
            message=cleaned_data["message"],
            from_email=self.request.user.email,
            recipient_list=[cleaned_data["recipient"].email],
            fail_silently=True,
        )

3 View Complete Implementation : models.py
Copyright GNU General Public License v2.0
Author : blackye
    def get_date_error_message(self, date_check):
        return ugettext("Please correct the duplicate data for %(field_name)s "
            "which must be unique for the %(lookup)s in %(date_field)s.") % {
            'field_name': date_check[2],
            'date_field': date_check[3],
            'lookup': six.text_type(date_check[1]),
        }

3 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : edisonlz
    def clean_url(self):
        url = self.cleaned_data['url']
        if not url.startswith('/'):
            raise forms.ValidationError(
                ugettext("URL is missing a leading slash."),
                code='missing_leading_slash',
            )
        if (settings.APPEND_SLASH and
            'django.middleware.common.CommonMiddleware' in settings.MIDDLEWARE_CLastES and
            not url.endswith('/')):
            raise forms.ValidationError(
                ugettext("URL is missing a trailing slash."),
                code='missing_trailing_slash',
            )
        return url

3 View Complete Implementation : chart.py
Copyright Apache License 2.0
Author : BeanWei
    def setup(self):
        super(ChartWidget, self).setup()

        self.charts = {}
        self.one_chart = False
        model_admin = self.admin_site._registry[self.model]
        chart = self.chart

        if hasattr(model_admin, 'data_charts'):
            if chart and chart in model_admin.data_charts:
                self.charts = {chart: model_admin.data_charts[chart]}
                self.one_chart = True
                if self.satle is None:
                    self.satle = model_admin.data_charts[chart].get('satle')
            else:
                self.charts = model_admin.data_charts
                if self.satle is None:
                    self.satle = ugettext(
                        "%s Charts") % self.model._meta.verbose_name_plural

3 View Complete Implementation : views.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
@permission_required('support.delete_ticket')
def AdminClose(request, id=None):
    if id is None: id = request.GET.get('id')
    ticket = get_object_or_404(Ticket, pk=id)
    ticket.status = 40
    ticket.save()
    request.user.mesaj_set.create(mesaj=ugettext(u'Ticket closed.'))
    return HttpResponseRedirect('/admin/support/ticket')

3 View Complete Implementation : models.py
Copyright MIT License
Author : bpgc-cte
    def __str__(self):
        if self.is_addition():
            return ugettext('Added "%(object)s".') % {'object': self.object_repr}
        elif self.is_change():
            return ugettext('Changed "%(object)s" - %(changes)s') % {
                'object': self.object_repr,
                'changes': self.get_change_message(),
            }
        elif self.is_deletion():
            return ugettext('Deleted "%(object)s."') % {'object': self.object_repr}

        return ugettext('LogEntry Object')

3 View Complete Implementation : views.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : jsmesami
@login_required
@_editor
def delete(request, fruit):
    if request.method == 'POST':
        form = FruitDeleteForm(request.POST)
        if form.is_valid():
            fruit.deleted = True
            fruit.why_deleted = form.cleaned_data['reason']
            fruit.save()
            messages.success(request, ugettext('The marker has been deleted.'))
            return redirect(fruit)
    else:
        form = FruitDeleteForm()

    context = {
        'form': form,
    }

    return render(request, 'fruit/delete.html', context)

3 View Complete Implementation : action_producers.py
Copyright MIT License
Author : abelardopardo
    def process_post(
        self,
        request: http.HttpRequest,
        schedule_item: models.ScheduledOperation,
        op_payload: SessionPayload,
    ) -> http.HttpResponse:
        """Process the valid form."""
        if op_payload.get('confirm_items'):
            # Update information to carry to the filtering stage
            op_payload['button_label'] = ugettext('Schedule')
            op_payload['valuerange'] = 2
            op_payload['step'] = 2
            op_payload.store_in_session(request.session)

            return redirect('action:item_filter')

        # Go straight to the final step
        return self.finish(request, op_payload, schedule_item)

3 View Complete Implementation : models.py
Copyright MIT License
Author : maykinmedia
    def __str__(self):
        if self.object_id:
            return "{ct} - {pk}".format(
                ct=self.content_type.name,
                pk=self.object_id
            )

        return ugettext('TimelineLog Object')

3 View Complete Implementation : forms.py
Copyright MIT License
Author : bpgc-cte
    def clean_url(self):
        url = self.cleaned_data['url']
        if not url.startswith('/'):
            raise forms.ValidationError(
                ugettext("URL is missing a leading slash."),
                code='missing_leading_slash',
            )
        if (settings.APPEND_SLASH and (
                (settings.MIDDLEWARE and 'django.middleware.common.CommonMiddleware' in settings.MIDDLEWARE) or
                'django.middleware.common.CommonMiddleware' in settings.MIDDLEWARE_CLastES) and
                not url.endswith('/')):
            raise forms.ValidationError(
                ugettext("URL is missing a trailing slash."),
                code='missing_trailing_slash',
            )
        return url

3 View Complete Implementation : search.py
Copyright MIT License
Author : meine-stadt-transparent
def _add_date_before(search, params, options, errors):
    """ Filters by a date given a string, catching parsing errors. """
    try:
        before = parse(params["before"])
    except (ValueError, OverflowError) as e:
        errors.append(
            ugettext(
                "The value for after is invalid. The correct format is YYYY-MM-DD or YYYY-MM-DD HH:MM:SS "
                + str(e)
            )
        )
        return search
    search = search.filter(
        Q("range", start={"lte": before}) | Q("range", legal_date={"lte": before})
    )
    options["before"] = before
    return search

3 View Complete Implementation : services.py
Copyright MIT License
Author : abelardopardo
def get_log_item(log_id: int) -> Optional[models.Log]:
    """Get the log object.

    Given a log_id, fetch it from the Logs table. This is the object used to
    write all the diagnostics.

    :param log_id: PK of the Log object to get
    :return:
    """
    log_item = models.Log.objects.filter(pk=log_id).first()
    if not log_item:
        # Not much can be done here. Call has no place to report error...
        LOGGER.error(
            ugettext('Incorrect execution request with log_id %s'),
            str(log_id))

    return log_item

3 View Complete Implementation : importdbtranslations.py
Copyright GNU Affero General Public License v3.0
Author : nextcloud
    def _import_translations(self, model, fields, language_code):
        """
        Import translations for fields on a model for a language code
        :param model: the translated model
        :param fields: the attributes to translate
        :param language_code: the language code
        :return:
        """
        for obj in model.objects.all():
            with switch_language(obj, language_code):
                if obj.has_translation(language_code):
                    obj.delete_translation(language_code)
                source = [self._get_en(obj, field) for field in fields]
                translations = [ugettext(value) for value in source]
                for field, translation in zip(fields, translations):
                    setattr(obj, field, translation)
                    obj.save()

3 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : drexly
    def clean_url(self):
        url = self.cleaned_data['url']
        if not url.startswith('/'):
            raise forms.ValidationError(
                ugettext("URL is missing a leading slash."),
                code='missing_leading_slash',
            )
        if (settings.APPEND_SLASH and
                'django.middleware.common.CommonMiddleware' in settings.MIDDLEWARE_CLastES and
                not url.endswith('/')):
            raise forms.ValidationError(
                ugettext("URL is missing a trailing slash."),
                code='missing_trailing_slash',
            )
        return url

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : savoirfairelinux
    def test_post_invalid_form(self):
        """Invalid form."""
        response = self.client.get(reverse_lazy('delivery:meal'))
        req = {}
        req['_update'] = 'Next: Print Kitchen Count'
        req['maindish'] = 'wrong'
        response = self.client.post(reverse_lazy('delivery:meal'), req)

        self.astertIn(
            ugettext(
                'Select a valid choice. That choice is not one of '
                'the available choices.').encode(response.charset),
            response.content
        )

3 View Complete Implementation : admin.py
Copyright GNU Affero General Public License v3.0
Author : ra-systems
    def __init__(self, request, model, list_display, list_display_links, list_filter, date_hierarchy, search_fields,
                 list_select_related, list_per_page, list_max_show_all, list_editable, model_admin, sortable_by):
        super(RaChangeList, self).__init__(request, model, list_display, list_display_links, list_filter,
                                           date_hierarchy, search_fields, list_select_related, list_per_page,
                                           list_max_show_all, list_editable, model_admin, sortable_by)
        self.request = request  # Add request to the clast
        if self.is_popup:
            satle = ugettext('Select %s')
        else:
            satle = ugettext('%s')
        self.satle = satle % force_text(self.opts.verbose_name_plural)

        self.no_records_message = model_admin.no_records_message

3 View Complete Implementation : models.py
Copyright Apache License 2.0
Author : edisonlz
    def __str__(self):
        if self.action_flag == ADDITION:
            return ugettext('Added "%(object)s".') % {'object': self.object_repr}
        elif self.action_flag == CHANGE:
            return ugettext('Changed "%(object)s" - %(changes)s') % {
                'object': self.object_repr,
                'changes': self.change_message,
            }
        elif self.action_flag == DELETION:
            return ugettext('Deleted "%(object)s."') % {'object': self.object_repr}

        return ugettext('LogEntry Object')

3 View Complete Implementation : forms.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : wagtail
    def clean(self):
        # Confirm that at least one reviewer has been specified.
        # Do this as a custom validation step (rather than pasting min_num=1 /
        # validate_min=True to inlineformset_factory) so that we can have a
        # custom error message.
        if (self.total_form_count() - len(self.deleted_forms) < 1):
            raise ValidationError(
                ugettext("Please select one or more reviewers."),
                code='too_few_forms'
            )

3 View Complete Implementation : models.py
Copyright MIT License
Author : Arx-Game
    def __unicode__(self):
        str = u'%s ' % self.field
        if not self.new_value:
            str += ugettext('removed')
        elif not self.old_value:
            str += ugettext('set to %s') % self.new_value
        else:
            str += ugettext('changed from "%(old_value)s" to "%(new_value)s"') % {
                'old_value': self.old_value,
                'new_value': self.new_value
                }
        return str

3 View Complete Implementation : user_sessions.py
Copyright MIT License
Author : AcaciaTrading
@register.filter
def location(value):
    """
    Transform an IP address into an approximate location.

    Example output:

    * Zwolle, The Netherlands
    * ``<i>unknown</i>``
    """
    location = geoip() and geoip().city(value)
    if location and location['country_name']:
        if location['city']:
            return '%s, %s' % (location['city'], location['country_name'])
        else:
            return location['country_name']
    return mark_safe('<i>%s</i>' % ugettext('unknown'))

3 View Complete Implementation : models.py
Copyright GNU General Public License v2.0
Author : blackye
    def get_unique_error_message(self, unique_check):
        if len(unique_check) == 1:
            return ugettext("Please correct the duplicate data for %(field)s.") % {
                "field": unique_check[0],
            }
        else:
            return ugettext("Please correct the duplicate data for %(field)s, "
                "which must be unique.") % {
                    "field": get_text_list(unique_check, six.text_type(_("and"))),
                }

3 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : edisonlz
def validate_label(value):
    if not LABEL_RE.search(value):
        raise forms.ValidationError(ugettext(
            u"This value must contain only letters, "
            u"numbers, underscores, and '.' dots."
        ))
    else:
        return value

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : ra-systems
    def get_meta_data(self):
        model = registry.get_ra_model_by_name(self.kwargs['base_model'])
        verbose_name = model._meta.verbose_name
        verbose_name_plural = model._meta.verbose_name_plural
        is_bidi = get_language_bidi()
        if is_bidi:
            page_satle = '%s %s' % (ugettext('reports'), model._meta.verbose_name_plural)
        else:
            page_satle = '%s %s' % (model._meta.verbose_name_plural, ugettext('reports'))
        opts = model._meta
        return verbose_name, verbose_name_plural, page_satle, opts

0 View Complete Implementation : canvas_email.py
Copyright MIT License
Author : abelardopardo
def _refresh_and_retry_send(
    oauth_info,
    conversation_url: str,
    canvas_email_payload: Dict,
):
    """Refresh OAuth token and retry send.

    :param target_url: URL to use as target
    :param oauth_info: Object with the oauth information
    :param conversation_urL: URL to send the conversation
    :param canvas_email_payload: Dictionary with additional information
    :return:
    """
    # Request rejected due to token expiration. Refresh the
    # token
    user_token = None
    result_msg = ugettext('OAuth token refreshed')
    response_status = None
    try:
        user_token = services.refresh_token(user_token, oauth_info)
    except Exception as exc:
        result_msg = str(exc)

    if user_token:
        # Update the header with the new token
        headers = {
            'content-type':
                'application/x-www-form-urlencoded; charset=UTF-8',
            'Authorization': 'Bearer {0}'.format(
                user_token.access_token,
            ),
        }

        # Second attempt at executing the API call
        response = requests.post(
            url=conversation_url,
            data=canvas_email_payload,
            headers=headers)
        response_status = response.status_code

    return result_msg, response_status

0 View Complete Implementation : canvas_email.py
Copyright MIT License
Author : abelardopardo
def _send_single_canvas_message(
    conversation_url: str,
    canvas_email_payload,
    headers: Dict,
    oauth_info,
) -> Tuple[str, int]:
    """Send a single email to Canvas using the API.

    :param target_url: Target URL in the canvas server
    :param conversation_url: URL pointing to the conversation object
    :param canvas_email_payload: Email message
    :param headers: HTTP headers for the request
    :param oauth_info: Authentication info
    :return: response message, response status
    """
    result_msg = ugettext('Message successfuly sent')

    # Send the email through the API call
    # First attempt
    response = requests.post(
        url=conversation_url,
        data=canvas_email_payload,
        headers=headers)
    response_status = response.status_code

    req_rejected = (
        response.status_code == status.HTTP_401_UNAUTHORIZED
        and response.headers.get('WWW-Authenticate')
    )
    if req_rejected:
        result_msg, response_status = _refresh_and_retry_send(
            oauth_info,
            conversation_url,
            canvas_email_payload,
        )
    elif response_status != status.HTTP_201_CREATED:
        result_msg = ugettext(
            'Unable to deliver message (code {0})').format(
            response_status)

    return result_msg, response_status

0 View Complete Implementation : canvas_email.py
Copyright MIT License
Author : abelardopardo
    def process_run_post(
        self,
        request: http.HttpRequest,
        action: models.Action,
        payload: SessionPayload,
    ) -> http.HttpResponse:
        """Process the VALID POST request."""
        if payload.get('confirm_items'):
            # Create a dictionary in the session to carry over all the
            # information to execute the next pages
            payload['button_label'] = ugettext('Send')
            payload['valuerange'] = 2
            payload['step'] = 2
            continue_url = 'action:item_filter'
        else:
            continue_url = 'action:run_done'

        payload.store_in_session(request.session)

        # Check for the CANVAS token and proceed to the continue_url
        return _canvas_get_or_set_oauth_token(
            request,
            payload['target_url'],
            continue_url)

0 View Complete Implementation : run_manager.py
Copyright MIT License
Author : abelardopardo
    def process_run_post(
        self,
        request: http.HttpRequest,
        action: models.Action,
        payload: SessionPayload,
    ) -> http.HttpResponse:
        """Process the VALID POST request."""
        if payload.get('confirm_items'):
            # Add information to the session object to execute the next pages
            payload['button_label'] = ugettext('Send')
            payload['valuerange'] = 2
            payload['step'] = 2
            payload.store_in_session(request.session)

            return redirect('action:item_filter')

        # Go straight to the final step.
        return self.process_run_request_done(
            request,
            workflow=action.workflow,
            payload=payload,
            action=action)

0 View Complete Implementation : operands.py
Copyright MIT License
Author : abelardopardo
def less(node, eval_type, given_variables):
    """Process the less operator.

    :param node: Formula node
    :param eval_type: Type of evaluation
    :param given_variables: Dictionary of var/values
    :return: Boolean result, SQL query, or text result
    """
    constant = GET_CONSTANT.get(node['type'])(node['value'])

    if eval_type == EVAL_EXP:
        # Python evaluation
        varvalue = get_value(node, given_variables)
        if node['type'] in ('integer', 'double', 'datetime'):
            return (not value_is_null(varvalue)) and varvalue < constant
        raise Exception(
            ugettext(
                'Evaluation error: '
                + 'Type {0} not allowed with operator LESS',
            ).format(node['type']),
        )

    if eval_type == EVAL_SQL:
        # SQL evaluation
        query = sql.SQL('({0} < {1}) AND ({0} is not null)').format(
            OnTaskDBIdentifier(node['field']),
            sql.Placeholder(),
        )
        fields = [str(constant)]

        return query, fields

    # Text evaluation
    return '{0} < {1} and not empty'.format(
        node['field'], constant,
    )

0 View Complete Implementation : operands.py
Copyright MIT License
Author : abelardopardo
def less_or_equal(node, eval_type, given_variables):
    """Process the less_or_equal operator.

    :param node: Formula node
    :param eval_type: Type of evaluation
    :param given_variables: Dictionary of var/values
    :return: Boolean result, SQL query, or text result
    """
    constant = GET_CONSTANT.get(node['type'])(node['value'])

    if eval_type == EVAL_EXP:
        # Python evaluation
        varvalue = get_value(node, given_variables)
        if node['type'] in ('integer', 'double', 'datetime'):
            return (not value_is_null(varvalue)) and varvalue <= constant
        raise Exception(
            ugettext(
                'Evaluation error: Type {0} not allowed '
                + 'with operator LESS OR EQUAL',
            ).format(node['type']),
        )

    if eval_type == EVAL_SQL:
        # SQL evaluation
        query = sql.SQL('({0} <= {1}) AND ({0} is not null)').format(
            OnTaskDBIdentifier(node['field']),
            sql.Placeholder(),
        )
        fields = [str(constant)]

        return query, fields

    # Text evaluation
    return '{0} ⋜ {1} and not empty'.format(
        node['field'],
        constant,
    )

0 View Complete Implementation : operands.py
Copyright MIT License
Author : abelardopardo
def greater(
    node,
    eval_type: str,
    given_variables: Dict
) -> Union[bool, str, Tuple]:
    """Process the greater operator.

    :param node: Formula node
    :param eval_type: Type of evaluation
    :param given_variables: Dictionary of var/values
    :return: Boolean result, SQL query, or text result
    """
    constant = GET_CONSTANT.get(node['type'])(node['value'])

    if eval_type == EVAL_EXP:
        # Python evaluation
        varvalue = get_value(node, given_variables)
        if node['type'] in ('integer', 'double', 'datetime'):
            return (not value_is_null(varvalue)) and varvalue > constant
        raise Exception(
            ugettext(
                'Evaluation error: Type {0} not allowed '
                + 'with operator GREATER',
            ).format(node['type']),
        )

    if eval_type == EVAL_SQL:
        # SQL evaluation
        query = sql.SQL('({0} > {1}) AND ({0} is not null)').format(
            OnTaskDBIdentifier(node['field']),
            sql.Placeholder(),
        )
        fields = [str(constant)]

        return query, fields

    # Text evaluation
    return '{0} > {1} and not empty'.format(
        node['field'], constant,
    )

0 View Complete Implementation : operands.py
Copyright MIT License
Author : abelardopardo
def greater_or_equal(
    node,
    eval_type: str,
    given_variables: Dict
) -> Union[bool, str, Tuple]:
    """Process the greater_or_equal operator.

    :param node: Formula node
    :param eval_type: Type of evaluation
    :param given_variables: Dictionary of var/values
    :return: Boolean result, SQL query, or text result
    """
    constant = GET_CONSTANT.get(node['type'])(node['value'])

    if eval_type == EVAL_EXP:
        # Python evaluation
        varvalue = get_value(node, given_variables)
        if node['type'] in ('integer', 'double', 'datetime'):
            return (not value_is_null(varvalue)) and varvalue >= constant
        raise Exception(
            ugettext(
                'Evaluation error: Type {0} not allowed '
                + 'with operator GREATER OR EQUAL',
            ).format(node['type']),
        )

    if eval_type == EVAL_SQL:
        # SQL evaluation
        query = sql.SQL('({0} >= {1}) AND ({0} is not null)').format(
            OnTaskDBIdentifier(node['field']),
            sql.Placeholder(),
        )
        fields = [str(constant)]

        return query, fields

    # Text evaluation
    return '{0} ⋝ {1} and not empty'.format(
        node['field'],
        constant,
    )

0 View Complete Implementation : operands.py
Copyright MIT License
Author : abelardopardo
def between(
    node,
    eval_type: str,
    given_variables: Dict
) -> Union[bool, str, Tuple]:
    """Process the between operator.

    :param node: Formula node
    :param eval_type: Type of evaluation
    :param given_variables: Dictionary of var/values
    :return: Boolean result, SQL query, or text result
    """
    if eval_type == EVAL_EXP:
        # Python evaluation
        varvalue = get_value(node, given_variables)
        if value_is_null(varvalue):
            return False

        if node['type'] not in ('integer', 'double', 'datetime'):
            raise Exception(
                ugettext(
                    'Evaluation error: Type {0} not allowed '
                    + 'with operator BETWEEN',
                ).format(node['type']),
            )
        left = GET_CONSTANT[node['type']](node['value'][0])
        right = GET_CONSTANT[node['type']](node['value'][1])

        return left <= varvalue <= right

    if eval_type == EVAL_SQL:
        # SQL evaluation
        query = sql.SQL(
            '({0} BETWEEN {1} AND {2}) AND ({0} is not null)',
        ).format(
            OnTaskDBIdentifier(node['field']),
            sql.Placeholder(),
            sql.Placeholder(),
        )

        fields = [str(num) for num in node['value']]

        return query, fields

    # Text evaluation
    return '{0} ⋜ {1} ⋜ {2} and not empty'.format(
        str(node['value'][0]),
        node['field'],
        str(node['value'][1]),
    )

0 View Complete Implementation : operands.py
Copyright MIT License
Author : abelardopardo
def not_between(
    node,
    eval_type: str,
    given_variables: Dict,
) -> Union[bool, str, Tuple]:
    """Process the not_between operator.

    :param node: Formula node
    :param eval_type: Type of evaluation
    :param given_variables: Dictionary of var/values
    :return: Boolean result, SQL query, or text result
    """
    if eval_type == EVAL_EXP:
        # Python evaluation
        varvalue = get_value(node, given_variables)
        if value_is_null(varvalue):
            return False

        if node['type'] not in ('integer', 'double', 'datetime'):
            raise Exception(
                ugettext(
                    'Evaluation error: Type {0} not allowed '
                    + 'with operator BETWEEN',
                ).format(node['type']),
            )
        left = GET_CONSTANT[node['type']](node['value'][0])
        right = GET_CONSTANT[node['type']](node['value'][1])

        return not left <= varvalue <= right

    if eval_type == EVAL_SQL:
        # SQL evaluation
        query = sql.SQL(
            '({0} NOT BETWEEN {1} AND {2}) AND ({0} is not null)',
        ).format(
            OnTaskDBIdentifier(node['field']),
            sql.Placeholder(),
            sql.Placeholder(),
        )

        fields = [str(number) for number in node['value']]

        return query, fields

    # Text evaluation
    return '{0} < {1} or {0} > {2} or {0} is empty'.format(
        node['field'],
        str(node['value'][0]),
        str(node['value'][1]),
    )

0 View Complete Implementation : increase_track.py
Copyright MIT License
Author : abelardopardo
    def execute_operation(
        self,
        user,
        workflow: Optional[models.Workflow] = None,
        action: Optional[models.Action] = None,
        payload: Optional[Dict] = None,
        log_item: Optional[models.Log] = None,
    ):
        """Process track requests asynchronously.

        :param user: User object
        :param workflow: Optional workflow object
        :param action: Optional action object
        :param payload: has fields method and get_dict with the request
        method and the get dictionary.
        :param log_item: Optional logitem object.
        :return: Nothing
        """
        del user, workflow, action, log_item
        method = payload.get('method')
        if method != 'GET':
            # Only GET requests are accepted
            raise Exception(ugettext('Non-GET request received in Track URL'))

        get_dict = payload.get('get_dict')
        if get_dict is None:
            raise Exception(ugettext('No dictionary in Track URL'))

        # Obtain the track_id from the request
        track_id = get_dict.get('v')
        if not track_id:
            raise Exception(ugettext('No track_id found in request'))

        # If the track_id is not correctly signed, finish.
        try:
            track_id = signing.loads(track_id)
        except signing.BadSignature:
            raise Exception(ugettext('Bad signature in track_id'))

        # The request is legit and the value has been verified. Track_id has
        # now the dictionary with the tracking information

        # Get the objects related to the ping
        user = get_user_model().objects.filter(
            email=track_id['sender']).first()
        if not user:
            raise Exception(
                ugettext('Incorrect user email %s'),
                track_id['sender'])

        action = models.Action.objects.filter(pk=track_id['action']).first()
        if not action:
            raise Exception(
                ugettext('Incorrect action id %s'),
                track_id['action'])

        # Extract the relevant fields from the track_id
        column_dst = track_id.get('column_dst', '')
        column_to = track_id.get('column_to', '')
        msg_to = track_id.get('to', '')

        column = action.workflow.columns.filter(name=column_dst).first()
        if not column:
            # If the column does not exist, we are done
            raise Exception(ugettext('Column %s does not exist'), column_dst)

        log_payload = {
            'to': msg_to,
            'email_column': column_to,
            'column_dst': column_dst}

        # If the track comes with column_dst, the event needs to be reflected
        # back in the data frame
        if column_dst:
            try:
                # Increase the relevant cell by one
                sql.increase_row_integer(
                    action.workflow.get_data_frame_table_name(),
                    column_dst,
                    column_to,
                    msg_to)
            except Exception as exc:
                log_payload['EXCEPTION_MSG'] = str(exc)
            else:
                # Get the tracking column and update all the conditions in the
                # actions that have this column as part of their formulas
                # FIX: Too aggressive?
                track_col = action.workflow.columns.get(name=column_dst)
                for action in action.workflow.actions.all():
                    action.update_n_rows_selected(track_col)

        # Record the event
        action.log(user, self.log_event, **log_payload)

0 View Complete Implementation : plugin_execute.py
Copyright MIT License
Author : abelardopardo
def _execute_plugin(
    workflow,
    plugin_info,
    input_column_names,
    output_column_names,
    output_suffix,
    merge_key,
    plugin_params,
):
    """
    Execute the run method in the plugin.

    Execute the run method in a plugin with the dataframe from the given
    workflow

    :param workflow: Workflow object being processed
    :param plugin_info: PluginReistry object being processed
    :param input_column_names: List of input column names
    :param output_column_names: List of output column names
    :param output_suffix: Suffix that is added to the output column names
    :param merge_key: Key column to use in the merge
    :param plugin_params: Dictionary with the parameters to execute the plug in
    :return: Nothing, the result is stored in the log with log_id
    """
    try:
        plugin_instance, msgs = load_plugin(plugin_info.filename)
    except OnTaskServiceException:
        raise Exception(
            ugettext('Unable to instantiate plugin "{0}"').format(
                plugin_info.name),
        )

    # Check that the list of given inputs is consistent: if plugin has a list
    # of inputs, it has to have the same length as the given list.
    if (
        plugin_instance.get_input_column_names()
        and len(plugin_instance.get_input_column_names())
        != len(input_column_names)
    ):
        raise Exception(
            ugettext(
                'Inconsistent number of inputs when invoking plugin "{0}"',
            ).format(plugin_info.name),
        )

    # Check that the list of given outputs has the same length as the list of
    # outputs proposed by the plugin
    if (
        plugin_instance.get_output_column_names()
        and len(plugin_instance.get_output_column_names())
        != len(output_column_names)
    ):
        raise Exception(
            ugettext(
                'Inconsistent number of outputs when invoking plugin "{0}"',
            ).format(plugin_info.name),
        )

    # Get the data frame from the workflow
    try:
        df = pandas.load_table(workflow.get_data_frame_table_name())
    except Exception as exc:
        raise Exception(
            ugettext(
                'Exception when retrieving the data frame from workflow: {0}',
            ).format(str(exc)),
        )

    # Set the updated names of the input, output columns, and the suffix
    if not plugin_instance.get_input_column_names():
        plugin_instance.input_column_names = input_column_names
    plugin_instance.output_column_names = output_column_names
    plugin_instance.output_suffix = output_suffix

    # Create a new dataframe with the given input columns, and rename them if
    # needed
    try:
        sub_df = pd.DataFrame(df[input_column_names])
        if plugin_instance.get_input_column_names():
            sub_df.columns = plugin_instance.get_input_column_names()
    except Exception as exc:
        raise Exception(ugettext(
            'Error when creating data frame for plugin: {0}',
        ).format(str(exc)))

    # Try the execution and catch any exception
    try:
        new_df = plugin_instance.run(sub_df, parameters=plugin_params)
    except Exception as exc:
        raise Exception(
            ugettext('Error while executing plugin: {0}').format(str(exc)),
        )

    # If plugin does not return a data frame, flag as error
    if not isinstance(new_df, pd.DataFrame):
        raise Exception(
            ugettext(
                'Plugin executed but did not return a pandas data frame.'),
        )

    # Execution is DONE. Now we have to perform various additional checks

    # Result has to have the exact same number of rows
    if new_df.shape[0] != df.shape[0]:
        raise Exception(
            ugettext(
                'Incorrect number of rows ({0}) in result data frame.',
            ).format(new_df.shape[0]),
        )

    # Merge key name cannot be part of the output df
    if merge_key in new_df.columns:
        raise Exception(
            ugettext(
                'Column name {0} cannot be in the result data frame.'.format(
                    merge_key)),
        )

    # Result column names are consistent
    if set(new_df.columns) != set(plugin_instance.get_output_column_names()):
        raise Exception(ugettext('Incorrect columns in result data frame.'))

    # Add the merge column to the result df
    new_df[merge_key] = df[merge_key]

    # Proceed with the merge
    try:
        new_frame = pandas.perform_dataframe_upload_merge(
            workflow,
            df,
            new_df,
            {
                'how_merge': 'inner',
                'dst_selected_key': merge_key,
                'src_selected_key': merge_key,
                'initial_column_names': list(new_df.columns),
                'rename_column_names': list(new_df.columns),
                'columns_to_upload': [True] * len(list(new_df.columns)),
            },
        )
    except Exception as exc:
        raise Exception(
            ugettext('Error while merging result: {0}.').format(str(exc)),
        )

    if isinstance(new_frame, str):
        raise Exception(
            ugettext('Error while merging result: {0}.').format(new_frame))

    # Update execution time in the plugin
    plugin_info.executed = datetime.now(
        pytz.timezone(settings.TIME_ZONE),
    )
    plugin_info.save()

    return True

0 View Complete Implementation : plugin_execute.py
Copyright MIT License
Author : abelardopardo
    def execute_operation(
        self,
        user,
        workflow: Optional[models.Workflow] = None,
        action: Optional[models.Action] = None,
        payload: Optional[Dict] = None,
        log_item: Optional[models.Log] = None,
    ):
        """Execute the plugin. Most of the parameters are in the payload.

        Execute the run method in a plugin with the dataframe from the given
        workflow and a payload with:

        - plugin_id: Id of the plugin being executed
        - input_column_names: List of input column names
        - output_column_names: List of output column names
        - output_suffix: Suffix that is added to the output column names
        - merge_key: Key column to use in the merge
        - parameters: Dictionary with the execution parameters
        """
        del action
        if not log_item and self.log_event:
            log_item = workflow.log(
                user,
                operation_type=self.log_event,
                **payload)

        try:
            # Get all the required information
            plugin_id = payload['plugin_id']
            input_column_names = payload['input_column_names']
            output_column_names = payload['output_column_names']
            output_suffix = payload['output_suffix']
            merge_key = payload['merge_key']
            parameters = payload['parameters']

            plugin_info = models.Plugin.objects.filter(pk=plugin_id).first()
            if not plugin_info:
                raise Exception(
                    ugettext('Unable to load plugin with id {pid}').format(
                        plugin_id),
                )

            # Set the status to "executing" before calling the function
            log_item.payload['status'] = 'Executing'
            log_item.save()

            # Invoke plugin execution
            _execute_plugin(
                workflow,
                plugin_info,
                input_column_names,
                output_column_names,
                output_suffix,
                merge_key,
                parameters)

            # Reflect status in the log event
            log_item.payload['status'] = 'Execution finished successfully'
            log_item.save()
        except Exception as exc:
            log_item.payload['status'] = ugettext(
                'Error: {0}').format(str(exc))
            log_item.save()

0 View Complete Implementation : services.py
Copyright MIT License
Author : abelardopardo
def log_table_server_side(
    request: http.HttpRequest,
    workflow: models.Workflow
) -> Dict:
    """Create the server side response for the table of logs.

    :param request: Http Request
    :param workflow: Workflow being considered.
    :return:
    """
    dt_page = DataTablesServerSidePaging(request)
    if not dt_page.is_valid:
        return http.JsonResponse(
            {'error': _('Incorrect request. Unable to process')},
        )

    # Get the logs
    qs = workflow.logs
    records_total = qs.count()

    if dt_page.search_value:
        # Refine the log
        qs = qs.filter(
            Q(id__icontains=dt_page.search_value)
            | Q(user__email__icontains=dt_page.search_value)
            | Q(name__icontains=dt_page.search_value)
            | Q(payload__icontains=dt_page.search_value),
            workflow__id=workflow.id,
        ).distinct()

    # Order and select values
    qs = qs.order_by(F('created').desc()).values_list(
        'id',
        'created',
        'user__email',
        'name',
    )
    records_filtered = qs.count()

    final_qs = []
    for log_item in qs[dt_page.start:dt_page.start + dt_page.length]:
        row = [
            '<a href="{0}" clast="spin"'.format(
                reverse('logs:view', kwargs={'pk': log_item[0]}),
            )
            + ' data-toggle="tooltip" satle="{0}">{1}</a>'.format(
                ugettext('View log content'),
                log_item[0],
            ),
            simplify_datetime_str(log_item[1]),
            log_item[2],
            log_item[3],
        ]

        # Add the row to the final query_set
        final_qs.append(row)

    return {
        'draw': dt_page.draw,
        'recordsTotal': records_total,
        'recordsFiltered': records_filtered,
        'data': final_qs,
    }

0 View Complete Implementation : action_producers.py
Copyright MIT License
Author : abelardopardo
    def _create_payload(self, **kwargs) -> SessionPayload:
        """Create a payload dictionary to store in the session.

        :param request: HTTP request
        :param operation_type: String denoting the type of s_item being
        processed
        :param s_item: Existing schedule item being processed (Optional)
        :param prev_url: String with the URL to use to "go back"
        :param action: Corresponding action for the schedule operation type, or
        if empty, it is contained in the scheduled_item (Optional)
        :return: Dictionary with pairs name: value
        """
        s_item = kwargs.get('schedule_item')
        action = kwargs.get('action')
        if s_item:
            action = s_item.action
            exclude_values = s_item.payload.get('exclude_values', [])
        else:
            exclude_values = []

        # Get the payload from the session, and if not, use the given one
        payload = SessionPayload(
            kwargs.get('request').session,
            initial_values={
                'action_id': action.id,
                'exclude_values': exclude_values,
                'operation_type': self.operation_type,
                'valuerange': list(range(2)),
                'prev_url': kwargs.get('prev_url'),
                'post_url': reverse('scheduler:finish_scheduling'),
                'page_satle': ugettext('Schedule Action Execution'),
            })
        if s_item:
            payload.update(s_item.payload)
            payload['schedule_id'] = s_item.id

        return payload

0 View Complete Implementation : items.py
Copyright MIT License
Author : abelardopardo
def create_timedelta_string(
    ftime: datetime,
    frequency: str,
    utime: Optional[datetime] = None,
) -> Optional[str]:
    """Create a string rendering a time delta between now and the given one.

    The rendering proceeds gradually to see if the words days, hours, minutes
    etc. are needed.

    :param ftime: datetime object (may be in the past)
    :param frequency: string with the cron frequency (or empty)
    :param utime: until datetime object
    :return: String rendering
    """
    diagnostic_msg = models.ScheduledOperation.validate_times(
        ftime,
        frequency,
        utime)
    if diagnostic_msg:
        return None

    now = datetime.now(pytz.timezone(settings.TIME_ZONE))

    if ftime and not frequency and not utime:
        # Single execution
        if ftime < now and not utime:
            return None

        return ftime.strftime('%H:%M:%S %z %Y/%b/%d')

    # Repeating execution.
    result = str(ExpressionDescriptor(
        frequency,
        casing_type=CasingTypeEnum.LowerCase))
    if not ftime and not utime:
        return result

    if ftime:
        # Has start time
        result = (
            ugettext('Starting at ')
            + ftime.strftime('%H:%M:%S %z %Y/%b/%d')
            + ', ' + result)

    if utime:
        # Has finish time
        result = result + ', until ' + utime.strftime('%H:%M:%S %z %Y/%b/%d')

    return result