当前位置: 首页>>代码示例>>Python>>正文


Python Webapp.get_region_ids方法代码示例

本文整理汇总了Python中mkt.webapps.models.Webapp.get_region_ids方法的典型用法代码示例。如果您正苦于以下问题:Python Webapp.get_region_ids方法的具体用法?Python Webapp.get_region_ids怎么用?Python Webapp.get_region_ids使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在mkt.webapps.models.Webapp的用法示例。


在下文中一共展示了Webapp.get_region_ids方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: fake_object

# 需要导入模块: from mkt.webapps.models import Webapp [as 别名]
# 或者: from mkt.webapps.models.Webapp import get_region_ids [as 别名]
    def fake_object(self, data):
        """Create a fake instance of Webapp and related models from ES data."""
        is_packaged = data['app_type'] != amo.ADDON_WEBAPP_HOSTED
        is_privileged = data['app_type'] == amo.ADDON_WEBAPP_PRIVILEGED

        obj = Webapp(id=data['id'], app_slug=data['app_slug'],
                     is_packaged=is_packaged, type=amo.ADDON_WEBAPP,
                     icon_type='image/png')

        # Set relations and attributes we need on those relations.
        # The properties set on latest_version and current_version differ
        # because we are only setting what the serializer is going to need.
        # In particular, latest_version.is_privileged needs to be set because
        # it's used by obj.app_type_id.
        obj.listed_authors = []
        obj._current_version = Version()
        obj._current_version.addon = obj
        obj._current_version._developer_name = data['author']
        obj._current_version.supported_locales = data['supported_locales']
        obj._current_version.version = data['current_version']
        obj._latest_version = Version()
        obj._latest_version.is_privileged = is_privileged
        obj._geodata = Geodata()
        obj.all_previews = [
            Preview(id=p['id'], modified=self.to_datetime(p['modified']),
            filetype=p['filetype'], sizes=p.get('sizes', {}))
            for p in data['previews']]
        obj.categories = data['category']
        obj._device_types = [DEVICE_TYPES[d] for d in data['device']]
        obj._is_disabled = data['is_disabled']

        # Set base attributes on the "fake" app using the data from ES.
        self._attach_fields(
            obj, data, ('created', 'modified', 'default_locale',
                        'icon_hash', 'is_escalated', 'is_offline',
                        'manifest_url', 'premium_type', 'regions', 'reviewed',
                        'status', 'weekly_downloads'))

        # Attach translations for all translated attributes.
        self._attach_translations(
            obj, data, ('name', 'description', 'homepage', 'release_notes',
                        'support_email', 'support_url'))
        if data.get('group_translations'):
            self._attach_translations(obj, data, ('group',))  # Feed group.
        else:
            obj.group_translations = None
        self._attach_translations(obj._geodata, data, ('banner_message',))

        # Set attributes that have a different name in ES.
        obj.public_stats = data['has_public_stats']

        # Override obj.get_region() with a static list of regions generated
        # from the region_exclusions stored in ES.
        obj.get_regions = obj.get_regions(obj.get_region_ids(
            restofworld=True, excluded=data['region_exclusions']))

        # Some methods below will need the raw data from ES, put it on obj.
        obj.es_data = data

        return obj
开发者ID:MorrisJobke,项目名称:zamboni,代码行数:62,代码来源:serializers.py

示例2: es_app_to_dict

# 需要导入模块: from mkt.webapps.models import Webapp [as 别名]
# 或者: from mkt.webapps.models.Webapp import get_region_ids [as 别名]
def es_app_to_dict(obj, region=None, profile=None, request=None):
    """
    Return app data as dict for API where `app` is the elasticsearch result.
    """
    # Circular import.
    from mkt.developers.models import AddonPaymentAccount
    from mkt.webapps.models import Installed, Webapp

    translation_fields = ('banner_message', 'description', 'homepage', 'name',
                          'release_notes', 'support_email', 'support_url')
    lang = None
    if request and request.method == 'GET' and 'lang' in request.GET:
        lang = request.GET.get('lang', '').lower()

    src = obj._source
    # The following doesn't perform a database query, but gives us useful
    # methods like `get_detail_url`. If you use `obj` make sure the calls
    # don't query the database.
    is_packaged = src.get('app_type') != amo.ADDON_WEBAPP_HOSTED
    app = Webapp(app_slug=obj.app_slug, is_packaged=is_packaged)

    attrs = ('created', 'current_version', 'default_locale', 'is_offline',
             'manifest_url', 'previews', 'reviewed', 'ratings', 'status',
             'weekly_downloads')
    data = dict((a, getattr(obj, a, None)) for a in attrs)

    # Flatten the localized fields from {'lang': ..., 'string': ...}
    # to {lang: string}.
    for field in translation_fields:
        src_field = '%s_translations' % field
        value_field = src.get(src_field)
        src[src_field] = dict((v.get('lang', ''), v.get('string', ''))
                              for v in value_field) if value_field else {}
        data[field] = get_translations(src, src_field, obj.default_locale,
                                       lang)

    if getattr(obj, 'content_ratings', None):
        for region_key in obj.content_ratings:
            obj.content_ratings[region_key] = dehydrate_content_rating(
                obj.content_ratings[region_key], region_key)

    data.update({
        'absolute_url': absolutify(app.get_detail_url()),
        'app_type': app.app_type,
        'author': src.get('author', ''),
        'banner_regions': src.get('banner_regions', []),
        'categories': [c for c in obj.category],
        'content_ratings': {
            'ratings': getattr(obj, 'content_ratings', {}),
            'descriptors': dehydrate_descriptors(
                getattr(obj, 'content_descriptors', {})),
            'interactive_elements': dehydrate_interactives(
                getattr(obj, 'interactive_elements', [])),
        },
        'device_types': [DEVICE_TYPES[d].api_name for d in src.get('device')],
        'icons': dict((i['size'], i['url']) for i in src.get('icons')),
        'id': str(obj._id),
        'is_packaged': is_packaged,
        'payment_required': False,
        'premium_type': amo.ADDON_PREMIUM_API[src.get('premium_type')],
        'privacy_policy': reverse('app-privacy-policy-detail',
                                  kwargs={'pk': obj._id}),
        'public_stats': obj.has_public_stats,
        'supported_locales': src.get('supported_locales', ''),
        'slug': obj.app_slug,
        # TODO: Remove the type check once this code rolls out and our indexes
        # aren't between mapping changes.
        'versions': dict((v.get('version'), v.get('resource_uri')) for v in
                         src.get('versions') if type(v) == dict),
    })

    if not data['public_stats']:
        data['weekly_downloads'] = None
    def serialize_region(o):
        d = {}
        for field in ('name', 'slug', 'mcc', 'adolescent'):
            d[field] = getattr(o, field, None)
        return d
    data['regions'] = [serialize_region(REGIONS_CHOICES_ID_DICT.get(k))
                       for k in app.get_region_ids(
                               worldwide=True,
                               excluded=obj.region_exclusions)]

    if src.get('premium_type') in amo.ADDON_PREMIUMS:
        acct = list(AddonPaymentAccount.objects.filter(addon=app))
        if acct and acct.payment_account:
            data['payment_account'] = reverse(
                'payment-account-detail',
                kwargs={'pk': acct.payment_account.pk})
    else:
        data['payment_account'] = None

    data['upsell'] = False
    if hasattr(obj, 'upsell'):
        exclusions = obj.upsell.get('region_exclusions')
        if exclusions is not None and region not in exclusions:
            data['upsell'] = obj.upsell
            data['upsell']['resource_uri'] = reverse(
                'app-detail',
                kwargs={'pk': obj.upsell['id']})
#.........这里部分代码省略.........
开发者ID:hardikj,项目名称:zamboni,代码行数:103,代码来源:utils.py

示例3: es_app_to_dict

# 需要导入模块: from mkt.webapps.models import Webapp [as 别名]
# 或者: from mkt.webapps.models.Webapp import get_region_ids [as 别名]
def es_app_to_dict(obj, region=None, profile=None, request=None):
    """
    Return app data as dict for API where `app` is the elasticsearch result.
    """
    # Circular import.
    from mkt.api.base import GenericObject
    from mkt.api.resources import AppResource, PrivacyPolicyResource
    from mkt.developers.api import AccountResource
    from mkt.developers.models import AddonPaymentAccount
    from mkt.webapps.models import Installed, Webapp

    src = obj._source
    # The following doesn't perform a database query, but gives us useful
    # methods like `get_detail_url`. If you use `obj` make sure the calls
    # don't query the database.
    is_packaged = src.get('app_type') != amo.ADDON_WEBAPP_HOSTED
    app = Webapp(app_slug=obj.app_slug, is_packaged=is_packaged)

    attrs = ('content_ratings', 'created', 'current_version', 'default_locale',
             'homepage', 'manifest_url', 'previews', 'ratings', 'status',
             'support_email', 'support_url', 'weekly_downloads')
    data = dict((a, getattr(obj, a, None)) for a in attrs)
    data.update({
        'absolute_url': absolutify(app.get_detail_url()),
        'app_type': app.app_type,
        'author': src.get('author', ''),
        'categories': [c for c in obj.category],
        'description': get_attr_lang(src, 'description', obj.default_locale),
        'device_types': [DEVICE_TYPES[d].api_name for d in src.get('device')],
        'icons': dict((i['size'], i['url']) for i in src.get('icons')),
        'id': str(obj._id),
        'is_packaged': is_packaged,
        'name': get_attr_lang(src, 'name', obj.default_locale),
        'payment_required': False,
        'premium_type': amo.ADDON_PREMIUM_API[src.get('premium_type')],
        'privacy_policy': PrivacyPolicyResource().get_resource_uri(
            GenericObject({'pk': obj._id})
        ),
        'public_stats': obj.has_public_stats,
        'supported_locales': src.get('supported_locales', ''),
        'slug': obj.app_slug,
        # TODO: Remove the type check once this code rolls out and our indexes
        # aren't between mapping changes.
        'versions': dict((v.get('version'), v.get('resource_uri')) for v in
                         src.get('versions') if type(v) == dict),
    })

    if not data['public_stats']:
        data['weekly_downloads'] = None

    data['regions'] = RegionResource().dehydrate_objects(
        map(REGIONS_CHOICES_ID_DICT.get,
            app.get_region_ids(worldwide=True,
                               excluded=obj.region_exclusions)))

    if src.get('premium_type') in amo.ADDON_PREMIUMS:
        acct = list(AddonPaymentAccount.objects.filter(addon=app))
        if acct and acct.payment_account:
            data['payment_account'] = AccountResource().get_resource_uri(
                acct.payment_account)
    else:
        data['payment_account'] = None

    data['upsell'] = False
    if hasattr(obj, 'upsell'):
        exclusions = obj.upsell.get('region_exclusions')
        if exclusions is not None and region not in exclusions:
            data['upsell'] = obj.upsell
            data['upsell']['resource_uri'] = AppResource().get_resource_uri(
                Webapp(id=obj.upsell['id']))

    data['price'] = data['price_locale'] = None
    try:
        price_tier = src.get('price_tier')
        if price_tier:
            price = Price.objects.get(name=price_tier)
            if (data['upsell'] or payments_enabled(request)):
                price_currency = price.get_price_currency(region=region)
                if price_currency and price_currency.paid:
                    data['price'] = price.get_price(region=region)
                    data['price_locale'] = price.get_price_locale(
                        region=region)
            data['payment_required'] = bool(price.price)
    except Price.DoesNotExist:
        log.warning('Issue with price tier on app: {0}'.format(obj._id))
        data['payment_required'] = True

    # TODO: Let's get rid of these from the API to avoid db hits.
    if profile and isinstance(profile, UserProfile):
        data['user'] = {
            'developed': AddonUser.objects.filter(addon=obj.id,
                user=profile, role=amo.AUTHOR_ROLE_OWNER).exists(),
            'installed': Installed.objects.filter(
                user=profile, addon_id=obj.id).exists(),
            'purchased': obj.id in profile.purchase_ids(),
        }

    return data
开发者ID:almosteverywhere,项目名称:zamboni,代码行数:100,代码来源:utils.py

示例4: fake_object

# 需要导入模块: from mkt.webapps.models import Webapp [as 别名]
# 或者: from mkt.webapps.models.Webapp import get_region_ids [as 别名]
    def fake_object(self, data):
        """Create a fake instance of Webapp and related models from ES data."""
        is_packaged = data["app_type"] != mkt.ADDON_WEBAPP_HOSTED
        is_privileged = data["app_type"] == mkt.ADDON_WEBAPP_PRIVILEGED

        obj = Webapp(id=data["id"], app_slug=data["app_slug"], is_packaged=is_packaged, icon_type="image/png")

        # Set relations and attributes we need on those relations.
        # The properties set on latest_version and current_version differ
        # because we are only setting what the serializer is going to need.
        # In particular, latest_version.is_privileged needs to be set because
        # it's used by obj.app_type_id.
        obj.listed_authors = []
        obj._current_version = Version()
        obj._current_version.addon = obj
        obj._current_version._developer_name = data["author"]
        obj._current_version.supported_locales = data["supported_locales"]
        obj._current_version.version = data["current_version"]
        obj._latest_version = Version()
        obj._latest_version.is_privileged = is_privileged
        obj._geodata = Geodata()
        obj.all_previews = [
            Preview(
                id=p["id"], modified=self.to_datetime(p["modified"]), filetype=p["filetype"], sizes=p.get("sizes", {})
            )
            for p in data["previews"]
        ]
        obj.categories = data["category"]
        obj._device_types = [DEVICE_TYPES[d] for d in data["device"]]
        obj._is_disabled = data["is_disabled"]

        # Set base attributes on the "fake" app using the data from ES.
        self._attach_fields(
            obj,
            data,
            (
                "created",
                "default_locale",
                "icon_hash",
                "is_escalated",
                "is_offline",
                "last_updated",
                "manifest_url",
                "modified",
                "premium_type",
                "regions",
                "reviewed",
                "status",
            ),
        )

        # Attach translations for all translated attributes.
        self._attach_translations(obj, data, ("name", "description", "homepage", "support_email", "support_url"))
        if data.get("group_translations"):
            self._attach_translations(obj, data, ("group",))  # Feed group.
        else:
            obj.group_translations = None
        self._attach_translations(obj._geodata, data, ("banner_message",))

        # Release notes target and source name differ (ES stores it as
        # release_notes but the db field we are emulating is called
        # releasenotes without the "_").
        ESTranslationSerializerField.attach_translations(
            obj._current_version, data, "release_notes", target_name="releasenotes"
        )

        # Set attributes that have a different name in ES.
        obj.public_stats = data["has_public_stats"]

        # Override obj.get_region() with a static list of regions generated
        # from the region_exclusions stored in ES.
        obj.get_regions = obj.get_regions(obj.get_region_ids(restofworld=True, excluded=data["region_exclusions"]))

        # Some methods below will need the raw data from ES, put it on obj.
        obj.es_data = data

        return obj
开发者ID:,项目名称:,代码行数:79,代码来源:

示例5: es_app_to_dict

# 需要导入模块: from mkt.webapps.models import Webapp [as 别名]
# 或者: from mkt.webapps.models.Webapp import get_region_ids [as 别名]

#.........这里部分代码省略.........
    for icon in icons:
        if 'url' in icon:
            # Old-style index, the full URL is already present, nothing to do.
            # TODO: remove this check once we have re-indexed everything.
            continue
        else:
            # New-style index, we need to build the URLs from the data we have.
            icon['url'] = app.get_icon_url(icon['size'])

    data.update({
        'absolute_url': absolutify(app.get_detail_url()),
        'app_type': 'packaged' if is_packaged else 'hosted',
        'author': src.get('author', ''),
        'banner_regions': src.get('banner_regions', []),
        'categories': [c for c in obj.category],
        'content_ratings': filter_content_ratings_by_region({
            'ratings': dehydrate_content_ratings(
                getattr(obj, 'content_ratings', {})),
            'descriptors': dehydrate_descriptors(
                getattr(obj, 'content_descriptors', {})),
            'interactive_elements': dehydrate_interactives(
                getattr(obj, 'interactive_elements', [])),
            'regions': mkt.regions.REGION_TO_RATINGS_BODY()
        }, region=region_slug),
        'device_types': [DEVICE_TYPES[d].api_name for d in src.get('device')],
        'icons': dict((i['size'], i['url']) for i in src.get('icons')),
        'id': long(obj._id),
        'is_packaged': is_packaged,
        'payment_required': False,
        'premium_type': amo.ADDON_PREMIUM_API[src.get('premium_type')],
        'previews': previews,
        'privacy_policy': reverse('app-privacy-policy-detail',
                                  kwargs={'pk': obj._id}),
        'public_stats': obj.has_public_stats,
        'supported_locales': src.get('supported_locales', ''),
        'slug': obj.app_slug,
        'versions': dict((v.get('version'), v.get('resource_uri')) for v in
                         src.get('versions')),
    })

    if not data['public_stats']:
        data['weekly_downloads'] = None

    def serialize_region(o):
        d = {}
        for field in ('name', 'slug', 'mcc', 'adolescent'):
            d[field] = getattr(o, field, None)
        return d

    data['regions'] = [serialize_region(REGIONS_CHOICES_ID_DICT.get(k))
                       for k in app.get_region_ids(
                           worldwide=True, excluded=obj.region_exclusions)]

    data['payment_account'] = None
    if src.get('premium_type') in amo.ADDON_PREMIUMS:
        try:
            acct = AddonPaymentAccount.objects.get(addon_id=src.get('id'))
            if acct.payment_account:
                data['payment_account'] = reverse(
                    'payment-account-detail',
                    kwargs={'pk': acct.payment_account.pk})
        except AddonPaymentAccount.DoesNotExist:
            pass  # Developer hasn't set up a payment account yet.

    data['upsell'] = False
    if hasattr(obj, 'upsell'):
        exclusions = obj.upsell.get('region_exclusions')
        if exclusions is not None and region_slug not in exclusions:
            data['upsell'] = obj.upsell
            data['upsell']['resource_uri'] = reverse(
                'app-detail',
                kwargs={'pk': obj.upsell['id']})

    data['price'] = data['price_locale'] = None
    try:
        price_tier = src.get('price_tier')
        if price_tier:
            price = Price.objects.get(name=price_tier)
            price_currency = price.get_price_currency(region=region_id)
            if price_currency and price_currency.paid:
                data['price'] = price.get_price(region=region_id)
                data['price_locale'] = price.get_price_locale(
                    region=region_id)
            data['payment_required'] = bool(price.price)
    except Price.DoesNotExist:
        log.warning('Issue with price tier on app: {0}'.format(obj._id))
        data['payment_required'] = True

    # TODO: Let's get rid of these from the API to avoid db hits.
    if profile and isinstance(profile, UserProfile):
        data['user'] = {
            'developed': AddonUser.objects.filter(
                addon=obj.id, user=profile,
                role=amo.AUTHOR_ROLE_OWNER).exists(),
            'installed': Installed.objects.filter(
                user=profile, addon_id=obj.id).exists(),
            'purchased': obj.id in profile.purchase_ids(),
        }

    return data
开发者ID:aricha,项目名称:zamboni,代码行数:104,代码来源:utils.py

示例6: create_fake_app

# 需要导入模块: from mkt.webapps.models import Webapp [as 别名]
# 或者: from mkt.webapps.models.Webapp import get_region_ids [as 别名]
    def create_fake_app(self, data):
        """Create a fake instance of Webapp and related models from ES data."""
        is_packaged = data['app_type'] != amo.ADDON_WEBAPP_HOSTED
        is_privileged = data['app_type'] == amo.ADDON_WEBAPP_PRIVILEGED

        obj = Webapp(id=data['id'], app_slug=data['app_slug'],
                     is_packaged=is_packaged, type=amo.ADDON_WEBAPP,
                     icon_type='image/png')

        # Set relations and attributes we need on those relations.
        # The properties set on latest_version and current_version differ
        # because we are only setting what the serializer is going to need.
        # In particular, latest_version.is_privileged needs to be set because
        # it's used by obj.app_type_id.
        obj.listed_authors = []
        obj._current_version = Version()
        obj._current_version.addon = obj
        obj._current_version._developer_name = data['author']
        obj._current_version.supported_locales = data['supported_locales']
        obj._current_version.version = data['current_version']
        obj._latest_version = Version()
        obj._latest_version.is_privileged = is_privileged
        obj._geodata = Geodata()
        obj.all_categories = [Category(slug=cat) for cat in data['category']]
        obj.all_previews = [Preview(id=p['id'], modified=p['modified'],
            filetype=p['filetype']) for p in data['previews']]
        obj._device_types = [DEVICE_TYPES[d] for d in data['device']]

        # Set base attributes on the "fake" app using the data from ES.
        # It doesn't mean they'll get exposed in the serializer output, that
        # depends on what the fields/exclude attributes in Meta.
        for field_name in ('created', 'modified', 'default_locale',
                           'is_escalated', 'is_offline', 'manifest_url',
                           'premium_type', 'regions', 'reviewed', 'status',
                           'weekly_downloads'):
            setattr(obj, field_name, data.get(field_name))

        # Attach translations for all translated attributes.
        for field_name in ('name', 'description', 'homepage', 'support_email',
                           'support_url'):
            ESTranslationSerializerField.attach_translations(obj,
                data, field_name)
        ESTranslationSerializerField.attach_translations(obj._geodata,
            data, 'banner_message')
        ESTranslationSerializerField.attach_translations(obj._current_version,
            data, 'release_notes', target_name='releasenotes')

        # Set attributes that have a different name in ES.
        obj.public_stats = data['has_public_stats']

        # Avoid a query for payment_account if the app is not premium.
        if not obj.is_premium():
            obj.payment_account = None

        # Override obj.get_region() with a static list of regions generated
        # from the region_exclusions stored in ES.
        obj.get_regions = obj.get_regions(obj.get_region_ids(restofworld=True,
            excluded=data['region_exclusions']))

        # Some methods below will need the raw data from ES, put it on obj.
        obj.es_data = data

        return obj
开发者ID:bdacode,项目名称:zamboni,代码行数:65,代码来源:serializers.py

示例7: es_app_to_dict

# 需要导入模块: from mkt.webapps.models import Webapp [as 别名]
# 或者: from mkt.webapps.models.Webapp import get_region_ids [as 别名]
def es_app_to_dict(obj, region=None, profile=None, request=None):
    """
    Return app data as dict for API where `app` is the elasticsearch result.
    """
    # Circular import.
    from mkt.api.base import GenericObject
    from mkt.api.resources import AppResource, PrivacyPolicyResource
    from mkt.developers.api import AccountResource
    from mkt.developers.models import AddonPaymentAccount
    from mkt.webapps.models import Installed, Webapp

    src = obj._source
    # The following doesn't perform a database query, but gives us useful
    # methods like `get_detail_url`. If you use `obj` make sure the calls
    # don't query the database.
    is_packaged = src.get("app_type") == amo.ADDON_WEBAPP_PACKAGED
    app = Webapp(app_slug=obj.app_slug, is_packaged=is_packaged)

    attrs = (
        "content_ratings",
        "created",
        "current_version",
        "default_locale",
        "homepage",
        "manifest_url",
        "previews",
        "ratings",
        "status",
        "support_email",
        "support_url",
        "weekly_downloads",
    )
    data = dict((a, getattr(obj, a, None)) for a in attrs)
    data.update(
        {
            "absolute_url": absolutify(app.get_detail_url()),
            "app_type": app.app_type,
            "author": src.get("author", ""),
            "categories": [c for c in obj.category],
            "description": get_attr_lang(src, "description", obj.default_locale),
            "device_types": [DEVICE_TYPES[d].api_name for d in src.get("device")],
            "icons": dict((i["size"], i["url"]) for i in src.get("icons")),
            "id": str(obj._id),
            "is_packaged": is_packaged,
            "name": get_attr_lang(src, "name", obj.default_locale),
            "payment_required": False,
            "premium_type": amo.ADDON_PREMIUM_API[src.get("premium_type")],
            "privacy_policy": PrivacyPolicyResource().get_resource_uri(GenericObject({"pk": obj._id})),
            "public_stats": obj.has_public_stats,
            "supported_locales": src.get("supported_locales", ""),
            "slug": obj.app_slug,
            # TODO: Remove the type check once this code rolls out and our indexes
            # aren't between mapping changes.
            "versions": dict((v.get("version"), v.get("resource_uri")) for v in src.get("versions") if type(v) == dict),
        }
    )

    if not data["public_stats"]:
        data["weekly_downloads"] = None

    data["regions"] = RegionResource().dehydrate_objects(
        map(REGIONS_CHOICES_ID_DICT.get, app.get_region_ids(worldwide=True, excluded=obj.region_exclusions))
    )

    if src.get("premium_type") in amo.ADDON_PREMIUMS:
        acct = list(AddonPaymentAccount.objects.filter(addon=app))
        if acct and acct.payment_account:
            data["payment_account"] = AccountResource().get_resource_uri(acct.payment_account)
    else:
        data["payment_account"] = None

    data["price"] = data["price_locale"] = None
    try:
        price_tier = src.get("price_tier")
        if price_tier:
            price = Price.objects.get(name=price_tier)
            if region in settings.PURCHASE_ENABLED_REGIONS or (
                request and waffle.flag_is_active(request, "allow-paid-app-search")
            ):
                data["price"] = price.get_price(region=region)
                data["price_locale"] = price.get_price_locale(region=region)
            data["payment_required"] = bool(price.price)
    except Price.DoesNotExist:
        log.warning("Issue with price tier on app: {0}".format(obj._id))
        data["payment_required"] = True

    data["upsell"] = False
    if hasattr(obj, "upsell") and region in settings.PURCHASE_ENABLED_REGIONS:
        data["upsell"] = obj.upsell
        data["upsell"]["resource_uri"] = AppResource().get_resource_uri(Webapp(id=obj.upsell["id"]))

    # TODO: Let's get rid of these from the API to avoid db hits.
    if profile and isinstance(profile, UserProfile):
        data["user"] = {
            "developed": AddonUser.objects.filter(addon=obj.id, user=profile, role=amo.AUTHOR_ROLE_OWNER).exists(),
            "installed": Installed.objects.filter(user=profile, addon_id=obj.id).exists(),
            "purchased": obj.id in profile.purchase_ids(),
        }

    return data
开发者ID:kmaglione,项目名称:zamboni,代码行数:102,代码来源:utils.py

示例8: create_fake_app

# 需要导入模块: from mkt.webapps.models import Webapp [as 别名]
# 或者: from mkt.webapps.models.Webapp import get_region_ids [as 别名]
    def create_fake_app(self, data):
        """Create a fake instance of Webapp and related models from ES data."""
        is_packaged = data["app_type"] != amo.ADDON_WEBAPP_HOSTED
        is_privileged = data["app_type"] == amo.ADDON_WEBAPP_PRIVILEGED

        obj = Webapp(
            id=data["id"],
            app_slug=data["app_slug"],
            is_packaged=is_packaged,
            type=amo.ADDON_WEBAPP,
            icon_type="image/png",
        )

        # Set relations and attributes we need on those relations.
        # The properties set on latest_version and current_version differ
        # because we are only setting what the serializer is going to need.
        # In particular, latest_version.is_privileged needs to be set because
        # it's used by obj.app_type_id.
        obj.listed_authors = []
        obj._current_version = Version()
        obj._current_version.addon = obj
        obj._current_version._developer_name = data["author"]
        obj._current_version.supported_locales = data["supported_locales"]
        obj._current_version.version = data["current_version"]
        obj._latest_version = Version()
        obj._latest_version.is_privileged = is_privileged
        obj._geodata = Geodata()
        obj.all_categories = [Category(slug=cat) for cat in data["category"]]
        obj.all_previews = [
            Preview(id=p["id"], modified=p["modified"], filetype=p["filetype"]) for p in data["previews"]
        ]
        obj._device_types = [DEVICE_TYPES[d] for d in data["device"]]

        # Set base attributes on the "fake" app using the data from ES.
        # It doesn't mean they'll get exposed in the serializer output, that
        # depends on what the fields/exclude attributes in Meta.
        for field_name in (
            "created",
            "modified",
            "default_locale",
            "icon_hash",
            "is_escalated",
            "is_offline",
            "manifest_url",
            "premium_type",
            "regions",
            "reviewed",
            "status",
            "weekly_downloads",
        ):
            setattr(obj, field_name, data.get(field_name))

        # Attach translations for all translated attributes.
        for field_name in ("name", "description", "homepage", "support_email", "support_url"):
            ESTranslationSerializerField.attach_translations(obj, data, field_name)
        ESTranslationSerializerField.attach_translations(obj._geodata, data, "banner_message")
        ESTranslationSerializerField.attach_translations(
            obj._current_version, data, "release_notes", target_name="releasenotes"
        )

        # Set attributes that have a different name in ES.
        obj.public_stats = data["has_public_stats"]

        # Override obj.get_region() with a static list of regions generated
        # from the region_exclusions stored in ES.
        obj.get_regions = obj.get_regions(obj.get_region_ids(restofworld=True, excluded=data["region_exclusions"]))

        # Some methods below will need the raw data from ES, put it on obj.
        obj.es_data = data

        return obj
开发者ID:KKcorps,项目名称:zamboni,代码行数:73,代码来源:serializers.py

示例9: es_app_to_dict

# 需要导入模块: from mkt.webapps.models import Webapp [as 别名]
# 或者: from mkt.webapps.models.Webapp import get_region_ids [as 别名]
def es_app_to_dict(obj, region=None, profile=None):
    """
    Return app data as dict for API where `app` is the elasticsearch result.
    """
    # Circular import.
    from mkt.api.base import GenericObject
    from mkt.api.resources import AppResource, PrivacyPolicyResource
    from mkt.developers.api import AccountResource
    from mkt.developers.models import AddonPaymentAccount
    from mkt.webapps.models import Installed, Webapp

    src = obj._source
    # The following doesn't perform a database query, but gives us useful
    # methods like `get_detail_url`. If you use `obj` make sure the calls
    # don't query the database.
    is_packaged = src['app_type'] == amo.ADDON_WEBAPP_PACKAGED
    app = Webapp(app_slug=obj.app_slug, is_packaged=is_packaged)

    attrs = ('content_ratings', 'current_version', 'default_locale',
             'homepage', 'manifest_url', 'previews', 'ratings', 'status',
             'support_email', 'support_url')
    data = dict(zip(attrs, attrgetter(*attrs)(obj)))
    data.update({
        'absolute_url': absolutify(app.get_detail_url()),
        'app_type': app.app_type,
        'categories': [c for c in obj.category],
        'description': get_attr_lang(src, 'description', obj.default_locale),
        'device_types': [DEVICE_TYPES[d].api_name for d in src['device']],
        'icons': dict((i['size'], i['url']) for i in src['icons']),
        'id': str(obj._id),
        'is_packaged': is_packaged,
        'listed_authors': [{'name': name} for name in src['authors']],
        'name': get_attr_lang(src, 'name', obj.default_locale),
        'premium_type': amo.ADDON_PREMIUM_API[src['premium_type']],
        'privacy_policy': PrivacyPolicyResource().get_resource_uri(
            GenericObject({'pk': obj._id})
        ),
        'public_stats': obj.has_public_stats,
        'summary': get_attr_lang(src, 'summary', obj.default_locale),
        'supported_locales': src.get('supported_locales', ''),
        'slug': obj.app_slug,
    })

    data['regions'] = RegionResource().dehydrate_objects(
        map(REGIONS_CHOICES_ID_DICT.get,
            app.get_region_ids(worldwide=True,
                               excluded=obj.region_exclusions)))

    if src['premium_type'] in amo.ADDON_PREMIUMS:
        acct = list(AddonPaymentAccount.objects.filter(addon=app))
        if acct and acct.payment_account:
            data['payment_account'] = AccountResource().get_resource_uri(
                acct.payment_account)
    else:
        data['payment_account'] = None

    data['price'] = data['price_locale'] = None
    try:
        if src['price_tier']:
            price = Price.objects.get(name=src['price_tier'])
            data['price'] = price.get_price(region=region)
            data['price_locale'] = price.get_price_locale(region=region)
    except (Price.DoesNotExist, KeyError):
        log.warning('Issue with price tier on app: {0}'.format(obj._id))

    data['upsell'] = False
    if hasattr(obj, 'upsell'):
        data['upsell'] = obj.upsell
        data['upsell']['resource_uri'] = AppResource().get_resource_uri(
            Webapp(id=obj.upsell['id']))

    # TODO: Let's get rid of these from the API to avoid db hits.
    if profile and isinstance(profile, UserProfile):
        data['user'] = {
            'developed': AddonUser.objects.filter(
                user=profile, role=amo.AUTHOR_ROLE_OWNER).exists(),
            'installed': Installed.objects.filter(
                user=profile, addon_id=obj.id).exists(),
            'purchased': obj.id in profile.purchase_ids(),
        }

    return data
开发者ID:KryDos,项目名称:zamboni,代码行数:84,代码来源:utils.py


注:本文中的mkt.webapps.models.Webapp.get_region_ids方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。