python类ugettext_lazy()的实例源码

views.py 文件源码 项目:mos-horizon 作者: Mirantis 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def object_download(request, container_name, object_path):
    try:
        obj = api.swift.swift_get_object(request, container_name, object_path,
                                         resp_chunk_size=swift.CHUNK_SIZE)
    except Exception:
        redirect = reverse("horizon:project:containers:index")
        exceptions.handle(request,
                          _("Unable to retrieve object."),
                          redirect=redirect)
    # Add the original file extension back on if it wasn't preserved in the
    # name given to the object.
    filename = object_path.rsplit(swift.FOLDER_DELIMITER)[-1]
    if not os.path.splitext(obj.name)[1] and obj.orig_name:
        name, ext = os.path.splitext(obj.orig_name)
        filename = "%s%s" % (filename, ext)
    response = http.StreamingHttpResponse(obj.data)
    safe_name = filename.replace(",", "")
    if six.PY2:
        safe_name = safe_name.encode('utf-8')
    response['Content-Disposition'] = 'attachment; filename="%s"' % safe_name
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Length'] = obj.bytes
    return response
forms.py 文件源码 项目:mos-horizon 作者: Mirantis 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def handle(self, request, data):
        try:
            if not data['parent']:
                is_public = data["access"] == "public"
                metadata = ({'is_public': is_public})
                # Create a container
                api.swift.swift_create_container(request,
                                                 data["name"],
                                                 metadata=metadata)
                messages.success(request, _("Container created successfully."))
            else:
                # Create a pseudo-folder
                container, slash, remainder = data['parent'].partition("/")
                remainder = remainder.rstrip("/")
                subfolder_name = "/".join([bit for bit
                                           in (remainder, data['name'])
                                           if bit])
                api.swift.swift_create_subfolder(request,
                                                 container,
                                                 subfolder_name)
                messages.success(request, _("Folder created successfully."))
            return True
        except Exception:
            exceptions.handle(request, _('Unable to create container.'))
forms.py 文件源码 项目:mos-horizon 作者: Mirantis 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def handle(self, request, data):
        object_file = self.files.get('object_file')
        if object_file:
            object_path = self._set_object_path(data)
            try:
                obj = api.swift.swift_upload_object(request,
                                                    data['container_name'],
                                                    object_path,
                                                    object_file)
                messages.success(
                    request, _("Object was successfully updated."))
                return obj
            except Exception:
                exceptions.handle(request, _("Unable to update object."))
                return False
        else:
            # If object file is not provided, then a POST method is needed
            # to update ONLY metadata. This must be implemented when
            # object metadata can be updated from this panel.
            return True
views.py 文件源码 项目:mos-horizon 作者: Mirantis 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def get_data(self):
        try:
            volume_id = self.kwargs['volume_id']
            volume = cinder.volume_get(self.request, volume_id)
            snapshots = cinder.volume_snapshot_list(
                self.request, search_opts={'volume_id': volume.id})
            if snapshots:
                setattr(volume, 'has_snapshot', True)
            for att in volume.attachments:
                att['instance'] = api.nova.server_get(self.request,
                                                      att['server_id'])
        except Exception:
            redirect = self.get_redirect_url()
            exceptions.handle(self.request,
                              _('Unable to retrieve volume details.'),
                              redirect=redirect)
        return volume
views.py 文件源码 项目:mos-horizon 作者: Mirantis 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def _get_volume_types(self):
        try:
            volume_types = cinder.volume_type_list(self.request)
        except Exception:
            exceptions.handle(self.request,
                              _('Unable to retrieve volume type list.'))

        # check if we have default volume type so we can present the
        # description of no volume type differently
        no_type_description = None
        if self.default_vol_type is None:
            message = \
                _("If \"No volume type\" is selected, the volume will be "
                  "created without a volume type.")

            no_type_description = encoding.force_text(message)

        type_descriptions = [{'name': 'no_type',
                              'description': no_type_description}] + \
                            [{'name': type.name,
                              'description': getattr(type, "description", "")}
                             for type in volume_types]

        return json.dumps(type_descriptions)
views.py 文件源码 项目:mos-horizon 作者: Mirantis 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def get_context_data(self, **kwargs):
        context = super(CreateSnapshotView, self).get_context_data(**kwargs)
        context['volume_id'] = self.kwargs['volume_id']
        args = (self.kwargs['volume_id'],)
        context['submit_url'] = reverse(self.submit_url, args=args)
        try:
            volume = cinder.volume_get(self.request, context['volume_id'])
            if (volume.status == 'in-use'):
                context['attached'] = True
                context['form'].set_warning(_("This volume is currently "
                                              "attached to an instance. "
                                              "In some cases, creating a "
                                              "snapshot from an attached "
                                              "volume can result in a "
                                              "corrupted snapshot."))
            context['usages'] = quotas.tenant_limit_usages(self.request)
        except Exception:
            exceptions.handle(self.request,
                              _('Unable to retrieve volume information.'))
        return context
forms.py 文件源码 项目:mos-horizon 作者: Mirantis 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def prepare_source_fields_if_snapshot_specified(self, request):
        try:
            snapshot = self.get_snapshot(request,
                                         request.GET["snapshot_id"])
            self.fields['name'].initial = snapshot.name
            self.fields['size'].initial = snapshot.size
            self.fields['snapshot_source'].choices = ((snapshot.id,
                                                       snapshot),)
            try:
                # Set the volume type from the original volume
                orig_volume = cinder.volume_get(request,
                                                snapshot.volume_id)
                self.fields['type'].initial = orig_volume.volume_type
            except Exception:
                pass
            self.fields['size'].help_text = (
                _('Volume size must be equal to or greater than the '
                  'snapshot size (%sGiB)') % snapshot.size)
            del self.fields['image_source']
            del self.fields['volume_source']
            del self.fields['volume_source_type']
            del self.fields['availability_zone']
        except Exception:
            exceptions.handle(request,
                              _('Unable to load the specified snapshot.'))
forms.py 文件源码 项目:mos-horizon 作者: Mirantis 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def prepare_source_fields_if_volume_specified(self, request):
        self.fields['availability_zone'].choices = \
            availability_zones(request)
        volume = None
        try:
            volume = self.get_volume(request, request.GET["volume_id"])
        except Exception:
            msg = _('Unable to load the specified volume. %s')
            exceptions.handle(request, msg % request.GET['volume_id'])

        if volume is not None:
            self.fields['name'].initial = volume.name
            self.fields['description'].initial = volume.description
            min_vol_size = volume.size
            size_help_text = (_('Volume size must be equal to or greater '
                                'than the origin volume size (%sGiB)')
                              % volume.size)
            self.fields['size'].initial = min_vol_size
            self.fields['size'].help_text = size_help_text
            self.fields['volume_source'].choices = ((volume.id, volume),)
            self.fields['type'].initial = volume.type
            del self.fields['snapshot_source']
            del self.fields['image_source']
            del self.fields['volume_source_type']
forms.py 文件源码 项目:mos-horizon 作者: Mirantis 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def __init__(self, request, *args, **kwargs):
        super(CreateForm, self).__init__(request, *args, **kwargs)
        volume_types = cinder.volume_type_list(request)
        self.fields['type'].choices = [("no_type", _("No volume type"))] + \
                                      [(type.name, type.name)
                                       for type in volume_types]
        if 'initial' in kwargs and 'type' in kwargs['initial']:
            # if there is a default volume type to select, then remove
            # the first ""No volume type" entry
            self.fields['type'].choices.pop(0)

        if "snapshot_id" in request.GET:
            self.prepare_source_fields_if_snapshot_specified(request)
        elif 'image_id' in request.GET:
            self.prepare_source_fields_if_image_specified(request)
        elif 'volume_id' in request.GET:
            self.prepare_source_fields_if_volume_specified(request)
        else:
            self.prepare_source_fields_default(request)
tasks.py 文件源码 项目:socialhome 作者: jaywink 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def send_follow_notification(follower_id, followed_id):
    """Super simple you've been followed notification to a user."""
    if settings.DEBUG:
        return
    try:
        user = User.objects.get(profile__id=followed_id, is_active=True)
    except User.DoesNotExist:
        logger.warning("No active user with profile %s found for follow notification", followed_id)
        return
    try:
        follower = Profile.objects.get(id=follower_id)
    except Profile.DoesNotExist:
        logger.warning("No follower profile %s found for follow notifications", follower_id)
        return
    logger.info("send_follow_notification - Sending mail to %s", user.email)
    subject = _("New follower: %s" % follower.handle)
    context = get_common_context()
    context.update({
        "subject": subject, "actor_name": follower.name_or_handle,
        "actor_url": "%s%s" % (settings.SOCIALHOME_URL, follower.get_absolute_url()),
        "name": user.profile.name_or_handle,
    })
    send_mail(
        "%s%s" % (settings.EMAIL_SUBJECT_PREFIX, subject),
        render_to_string("notifications/follow.txt", context=context),
        settings.DEFAULT_FROM_EMAIL,
        [user.email],
        fail_silently=False,
        html_message=render_to_string("notifications/follow.html", context=context),
    )
tasks.py 文件源码 项目:socialhome 作者: jaywink 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def send_reply_notifications(content_id):
    """Super simple reply notification to content local participants.

    Until proper notifications is supported, just pop out an email.
    """
    if settings.DEBUG:
        return
    try:
        content = Content.objects.get(id=content_id, content_type=ContentType.REPLY)
    except Content.DoesNotExist:
        logger.warning("No reply content found with id %s", content_id)
        return
    root_content = content.root
    exclude_user = content.author.user if content.local else None
    participants = get_root_content_participants(root_content, exclude_user=exclude_user)
    if not participants:
        return
    subject = _("New reply to: %s" % root_content.short_text_inline)
    # TODO use fragment url to reply directly when available
    content_url = "%s%s" % (settings.SOCIALHOME_URL, root_content.get_absolute_url())
    context = get_common_context()
    context.update({
        "subject": subject, "actor_name": content.author.name_or_handle,
        "actor_url": "%s%s" % (settings.SOCIALHOME_URL, content.author.get_absolute_url()),
        "reply_text": content.text, "reply_rendered": content.rendered, "reply_url": content_url,
    })
    for participant in participants:
        context["name"] = participant.profile.name_or_handle
        logger.info("send_reply_notifications - Sending mail to %s", participant.email)
        send_mail(
            "%s%s" % (settings.EMAIL_SUBJECT_PREFIX, subject),
            render_to_string("notifications/reply.txt", context=context),
            settings.DEFAULT_FROM_EMAIL,
            [participant.email],
            fail_silently=False,
            html_message=render_to_string("notifications/reply.html", context=context),
        )
forms.py 文件源码 项目:django-codenerix-products 作者: centrologic 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def __groups__(self):
        g = [
            (
                _('Details'), 12,
                ['name', 6],
                ['tax', 3],
                ['default', 3],
                ['recargo_equivalencia', 4],

            )
        ]
        return g
forms.py 文件源码 项目:django-codenerix-products 作者: centrologic 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def __groups_details__():
        g = [
            (
                _('Details'), 12,
                ['name', 6],
                ['tax', 3],
                ['default', 3],
                ['recargo_equivalencia', 4],
            )
        ]
        return g
forms.py 文件源码 项目:django-codenerix-products 作者: centrologic 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def clean(self):
        cleaned_data = super(FeatureForm, self).clean()
        type_value = cleaned_data.get("type_value")
        list_value = cleaned_data.get("list_value")

        if type_value == TYPE_VALUES[2][0] and list_value is None:
            self._errors["type_value"] = ErrorList([_("Debe elegir un lista de valores")])
forms.py 文件源码 项目:django-codenerix-products 作者: centrologic 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def clean(self):
        cleaned_data = super(FeatureSpecialForm, self).clean()
        type_value = cleaned_data.get("type_value")
        list_value = cleaned_data.get("list_value")

        if type_value == TYPE_VALUES[2][0] and list_value is None:
            self._errors["type_value"] = ErrorList([_("Debe elegir un lista de valores")])
forms.py 文件源码 项目:django-codenerix-products 作者: centrologic 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def __groups__(self):
        g = [
            (
                _('Details'), 12,
                ['order', 2],
                ['code', 4],
                ['public', 3],
                ['show_menu', 3],
                ['icon', 6],
                ['image', 6],
            )
        ]
        return g
forms.py 文件源码 项目:django-codenerix-products 作者: centrologic 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def __groups__(self):
        g = [
            (
                _('Details'), 12,
                ['order', 2],
                ['code', 2],
                ['family', 4],
                ['public', 1],
                ['show_menu', 1],
                ['show_only_product_stock', 2],
                ['icon', 6],
                ['image', 6],
            )
        ]
        return g
forms.py 文件源码 项目:django-codenerix-products 作者: centrologic 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def __groups_details__():
        g = [
            (
                _('Details'), 12,
                ['order', 2],
                ['code', 4],
                ['family', 4],
                ['public', 1],
                ['show_menu', 1],
                ['show_only_product_stock', 2],
                ['image', 6],
                ['icon', 6],
            )
        ]
        return g
forms.py 文件源码 项目:django-codenerix-products 作者: centrologic 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def __groups__(self):
        g = [
            (
                _('Details'), 12,
                ['order', 3],
                ['code', 3],
                ['public', 2],
                ['show_menu', 2],
                ['outstanding', 2],
                ['icon', 6],
                ['image', 6],
            )
        ]
        return g
forms.py 文件源码 项目:django-codenerix-products 作者: centrologic 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def __groups__(self):
        g = [
            (
                _('Details'), 12,
                ['code', 4],
                ['price_base', 4],
                ['public', 1],
                ['of_sales', 1],
                ['of_purchase', 1],
                ['force_stock', 1],
                ['model', 4],
                ['brand', 4],
                ['feature_special', 4],
                ['family', 4],
                ['category', 4],
                ['subcategory', 4],
                ['tax', 4],
                ['url_video', 4],
            ),
            (
                _('Packaging information'), 12,
                ['packing_cost', 4],
                ['weight', 4],
            )
        ]
        return g


问题


面经


文章

微信
公众号

扫码关注公众号