• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python tower._函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中tower._函数的典型用法代码示例。如果您正苦于以下问题:Python _函数的具体用法?Python _怎么用?Python _使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: form_valid

    def form_valid(self, form):
        """Custom form validation to support email changing.

        If user is already authenticated and reaches this points, it's
        an email changing procedure. Validate that email is good and
        save it in the database.

        Otherwise continue with the default django-browserid verification.
        """
        if not self.request.user.is_authenticated():
            return super(BrowserIDVerify, self).form_valid(form)

        failure_url = urlparams(reverse('phonebook:profile_edit'), bid_login_failed=1)
        self.assertion = form.cleaned_data['assertion']
        self.audience = get_audience(self.request)
        result = verify(self.assertion, self.audience)
        if not result:
            messages.error(self.request, _('Authentication failed.'))
            return redirect(failure_url)

        email = result['email']

        if User.objects.filter(email=email).exists():
            messages.error(self.request, _('Email already exists in the database.'))
            return redirect('phonebook:logout')

        user = self.request.user
        user.email = email
        user.save()
        return redirect('phonebook:profile_view', user.username)
开发者ID:Ppchiu,项目名称:mozillians,代码行数:30,代码来源:views.py


示例2: in_app_config

def in_app_config(request, addon_id, addon, webapp=True):
    inapp = addon.premium_type in amo.ADDON_INAPPS
    if not inapp:
        messages.error(request,
                       _('Your app is not configured for in-app payments.'))
        return redirect(reverse('mkt.developers.apps.payments',
                                args=[addon.app_slug]))
    try:
        account = addon.app_payment_account
    except ObjectDoesNotExist:
        messages.error(request, _('No payment account for this app.'))
        return redirect(reverse('mkt.developers.apps.payments',
                                args=[addon.app_slug]))

    seller_config = get_seller_product(account)

    owner = acl.check_addon_ownership(request, addon)
    if request.method == 'POST':
        # Reset the in-app secret for the app.
        (client.api.generic
               .product(seller_config['resource_pk'])
               .patch(data={'secret': generate_key(48)}))
        messages.success(request, _('Changes successfully saved.'))
        return redirect(reverse('mkt.developers.apps.in_app_config',
                                args=[addon.app_slug]))

    return jingo.render(request, 'developers/payments/in-app-config.html',
                        {'addon': addon, 'owner': owner,
                         'seller_config': seller_config})
开发者ID:at13,项目名称:zamboni,代码行数:29,代码来源:views_payments.py


示例3: twitter_post

def twitter_post(request):
    """Post a tweet, and return a rendering of it (and any replies)."""

    try:
        reply_to_id = int(request.POST.get('reply_to', ''))
    except ValueError:
        # L10n: the tweet needs to be a reply to another tweet.
        return HttpResponseBadRequest(_('Reply-to is empty'))

    content = request.POST.get('content', '')
    if len(content) == 0:
        # L10n: the tweet has no content.
        return HttpResponseBadRequest(_('Message is empty'))

    if len(content) > 140:
        return HttpResponseBadRequest(_('Message is too long'))

    try:
        credentials = request.twitter.api.verify_credentials()
        username = credentials['screen_name']
        if username in settings.CC_BANNED_USERS:
            return render(request, 'customercare/tweets.html',
                          {'tweets': []})
        result = request.twitter.api.update_status(
            status=content,
            in_reply_to_status_id=reply_to_id)
    except (TwythonError, TwythonAuthError), e:
        # L10n: {message} is an error coming from our twitter api library
        return HttpResponseBadRequest(
            _('An error occured: {message}').format(message=e))
开发者ID:Acidburn0zzz,项目名称:kitsune,代码行数:30,代码来源:views.py


示例4: emailchange

def emailchange(request, user_id, token, hash):
    user = get_object_or_404(UserProfile, id=user_id)

    try:
        _uid, newemail = EmailResetCode.parse(token, hash)
    except ValueError:
        return http.HttpResponse(status=400)

    if _uid != user.id:
        # I'm calling this a warning because invalid hashes up to this point
        # could be any number of things, but this is a targeted attack from
        # one user account to another
        log.warning((u"[Tampering] Valid email reset code for UID (%s) "
                     "attempted to change email address for user (%s)")
                                                        % (_uid, user))
        return http.HttpResponse(status=400)

    user.email = newemail
    user.save()

    l = {'user': user, 'newemail': newemail}
    log.info(u"User (%(user)s) confirmed new email address (%(newemail)s)" % l)
    messages.success(request, _('Your email address was changed successfully'),
            _(u'From now on, please use {0} to log in.').format(newemail))

    return http.HttpResponseRedirect(reverse('users.edit'))
开发者ID:dimonov,项目名称:zamboni,代码行数:26,代码来源:views.py


示例5: setup_viewer

def setup_viewer(request, file_obj):
    data = {
        "file": file_obj,
        "version": file_obj.version,
        "addon": file_obj.version.addon,
        "status": False,
        "selected": {},
        "validate_url": "",
    }

    if acl.check_reviewer(request) or acl.check_addon_ownership(
        request, file_obj.version.addon, viewer=True, ignore_disabled=True
    ):
        data["validate_url"] = reverse(
            "mkt.developers.apps.json_file_validation", args=[file_obj.version.addon.app_slug, file_obj.id]
        )

    if acl.check_reviewer(request):
        data["file_link"] = {
            "text": _("Back to review"),
            "url": reverse("reviewers.apps.review", args=[data["addon"].app_slug]),
        }
    else:
        data["file_link"] = {"text": _("Back to app"), "url": reverse("detail", args=[data["addon"].pk])}
    return data
开发者ID:rhelmer,项目名称:zamboni,代码行数:25,代码来源:views.py


示例6: answer_vote

def answer_vote(request, question_id, answer_id):
    """Vote for Helpful/Not Helpful answers"""
    answer = get_object_or_404(Answer, pk=answer_id, question=question_id)
    if answer.question.is_locked:
        raise PermissionDenied

    if not answer.has_voted(request):
        vote = AnswerVote(answer=answer)

        if 'helpful' in request.REQUEST:
            vote.helpful = True
            AnswerMarkedHelpfulAction(answer.creator).save()
            message = _('Glad to hear it!')
        else:
            AnswerMarkedNotHelpfulAction(answer.creator).save()
            message = _('Sorry to hear that.')

        if request.user.is_authenticated():
            vote.creator = request.user
        else:
            vote.anonymous_id = request.anonymous.anonymous_id

        vote.save()
        ua = request.META.get('HTTP_USER_AGENT')
        if ua:
            vote.add_metadata('ua', ua[:1000])  # 1000 max_length
        statsd.incr('questions.votes.answer')
    else:
        message = _('You already voted on this reply.')

    if request.is_ajax():
        return HttpResponse(json.dumps({'message': message}))

    return HttpResponseRedirect(answer.get_absolute_url())
开发者ID:victorneo,项目名称:kitsune,代码行数:34,代码来源:views.py


示例7: api

def api(request):
    try:
        access = Access.objects.get(user=request.user)
    except Access.DoesNotExist:
        access = None

    roles = request.amo_user.groups.all()
    if roles:
        messages.error(request, _('Users with roles cannot use the API.'))

    elif not request.amo_user.read_dev_agreement:
        messages.error(request, _('You must accept the terms of service.'))

    elif request.method == 'POST':
        if 'delete' in request.POST:
            if access:
                access.delete()
                messages.success(request, _('API key deleted.'))

        else:
            if not access:
                key = 'mkt:%s:%s' % (request.amo_user.pk,
                                     request.amo_user.email)
                access = Access.objects.create(key=key, user=request.user,
                                               secret=generate())
            else:
                access.update(secret=generate())
            messages.success(request, _('New API key generated.'))

        return redirect(reverse('mkt.developers.apps.api'))

    return jingo.render(request, 'developers/api.html',
                        {'consumer': access, 'profile': profile,
                         'roles': roles})
开发者ID:bearstech,项目名称:zamboni,代码行数:34,代码来源:views.py


示例8: is_valid

    def is_valid(self, fatal=True):
        """
        Runs some overall archive checks.
        fatal: if the archive is not valid and fatal is True, it will raise
               an error, otherwise it will return False.
        """
        try:
            zip = zipfile.ZipFile(self.source, self.mode)
        except (BadZipfile, IOError):
            if fatal:
                log.info('Error extracting', exc_info=True)
                raise
            return False

        _info = zip.infolist()

        for info in _info:
            if '..' in info.filename or info.filename.startswith('/'):
                log.error('Extraction error, Invalid archive: %s' %
                          self.source)
                raise forms.ValidationError(_('Invalid archive.'))

            if info.file_size > settings.FILE_UNZIP_SIZE_LIMIT:
                log.error('Extraction error, file too big: %s, %s'
                          % (self.source, info.file_size))
                raise forms.ValidationError(_('Invalid archive.'))

        self.info = _info
        self.zip = zip
        return True
开发者ID:bearstech,项目名称:zamboni,代码行数:30,代码来源:utils.py


示例9: is_compatible

    def is_compatible(self):
        """Returns tuple of compatibility and reasons why if not.

        Server side conditions for determining compatibility are:
            * The add-on is an extension (not a theme, app, etc.)
            * Has not opted in to strict compatibility.
            * Does not use binary_components in chrome.manifest.

        Note: The lowest maxVersion compat check needs to be checked
              separately.
        Note: This does not take into account the client conditions.

        """
        compat = True
        reasons = []
        if self.addon.type != amo.ADDON_EXTENSION:
            compat = False
            # TODO: We may want this. For now we think it may be confusing.
            # reasons.append(_('Add-on is not an extension.'))
        if self.files.filter(binary_components=True).exists():
            compat = False
            reasons.append(_("Add-on uses binary components."))
        if self.files.filter(strict_compatibility=True).exists():
            compat = False
            reasons.append(_("Add-on has opted into strict compatibility " "checking."))
        return (compat, reasons)
开发者ID:syncopated,项目名称:zamboni,代码行数:26,代码来源:models.py


示例10: preload_submit

def preload_submit(request, addon_id, addon):
    if request.method == "POST":
        form = PreloadTestPlanForm(request.POST, request.FILES)
        if form.is_valid():
            # Save test plan file.
            test_plan = request.FILES["test_plan"]

            # Figure the type to save it as (cleaned as pdf/xls from the form).
            filetype = mimetypes.guess_type(test_plan.name)[0]
            if "pdf" in filetype:
                filename = "test_plan_%s.pdf"
            else:
                filename = "test_plan_%s.xls"

            # Timestamp.
            filename = filename % str(time.time()).split(".")[0]
            save_test_plan(request.FILES["test_plan"], filename, addon)

            # Log test plan.
            PreloadTestPlan.objects.filter(addon=addon).update(status=amo.STATUS_DISABLED)
            PreloadTestPlan.objects.create(addon=addon, filename=filename)

            messages.success(request, _("Application for preload successfully submitted."))
            return redirect(addon.get_dev_url("versions"))
        else:
            messages.error(request, _("There was an error with the form."))
    else:
        form = PreloadTestPlanForm()

    return render(request, "developers/apps/preload/submit.html", {"addon": addon, "form": form})
开发者ID:ngokevin,项目名称:zamboni,代码行数:30,代码来源:views.py


示例11: get_json_data

    def get_json_data(self, fileorpath):
        path = get_filepath(fileorpath)
        if zipfile.is_zipfile(path):
            zf = SafeUnzip(path)
            zf.is_valid()  # Raises forms.ValidationError if problems.
            try:
                data = zf.extract_path('manifest.webapp')
            except KeyError:
                raise forms.ValidationError(
                    _('The file "manifest.webapp" was not found at the root '
                      'of the packaged app archive.'))
        else:
            file_ = get_file(fileorpath)
            data = file_.read()
            file_.close()

        try:
            enc_guess = chardet.detect(data)
            data = strip_bom(data)
            decoded_data = data.decode(enc_guess['encoding'])
        except (ValueError, UnicodeDecodeError) as exc:
            msg = 'Error parsing webapp %r (encoding: %r %.2f%% sure): %s: %s'
            log.error(msg % (fileorpath, enc_guess['encoding'],
                             enc_guess['confidence'] * 100.0,
                             exc.__class__.__name__, exc))
            raise forms.ValidationError(
                _('Could not decode the webapp manifest file.'))

        try:
            return json.loads(decoded_data)
        except Exception:
            raise forms.ValidationError(
                _('The webapp manifest is not valid JSON.'))
开发者ID:bearstech,项目名称:zamboni,代码行数:33,代码来源:utils.py


示例12: sidebar

def sidebar(app):
    """Populates the sidebar with (categories, types)."""
    from addons.models import Category
    if app is None:
        return [], []

    # We muck with query to make order_by and extra_order_by play nice.
    q = Category.objects.filter(application=app.id, weight__gte=0,
                                type=amo.ADDON_EXTENSION)
    categories = order_by_translation(q, 'name')
    categories.query.extra_order_by.insert(0, 'weight')

    Type = collections.namedtuple('Type', 'id name url')
    base = urlresolvers.reverse('home')
    types = [Type(99, _('Collections'), base + 'collections/')]

    shown_types = {
        amo.ADDON_PERSONA: urlresolvers.reverse('browse.personas'),
        amo.ADDON_DICT: urlresolvers.reverse('browse.language-tools'),
        amo.ADDON_SEARCH: urlresolvers.reverse('browse.search-tools'),
        amo.ADDON_THEME: urlresolvers.reverse('browse.themes'),
    }
    titles = dict(amo.ADDON_TYPES,
                  **{amo.ADDON_DICT: _('Dictionaries & Language Packs')})
    for type_, url in shown_types.items():
        if type_ in app.types:
            types.append(Type(type_, titles[type_], url))

    return categories, sorted(types, key=lambda x: x.name)
开发者ID:JohnTheBeloved,项目名称:zamboni,代码行数:29,代码来源:helpers.py


示例13: del_image_async

def del_image_async(request, image_id):
    """Delete an image given its object id."""
    user = request.user
    if not user.is_authenticated():
        message = _('You are not logged in.')
        return HttpResponseForbidden(
            json.dumps({'status': 'error', 'message': message}))

    try:
        image = ImageAttachment.objects.get(pk=image_id)
    except ImageAttachment.DoesNotExist:
        message = _('The requested image could not be found.')
        return HttpResponseNotFound(
            json.dumps({'status': 'error', 'message': message}))

    if not ((user == image.creator) or
            (user.has_perm('upload.delete_imageattachment'))):
        message = _('You do not have permission to do that.')
        return HttpResponseForbidden(
            json.dumps({'status': 'error', 'message': message}))

    image.file.delete()
    if image.thumbnail:
        image.thumbnail.delete()
    image.delete()

    return HttpResponse(json.dumps({'status': 'success'}))
开发者ID:Acidburn0zzz,项目名称:kitsune,代码行数:27,代码来源:views.py


示例14: up_image_async

def up_image_async(request, model_name, object_pk):
    """Upload all images in request.FILES."""

    # Verify the model agaist our white-list
    if model_name not in ALLOWED_MODELS:
        message = _('Model not allowed.')
        return HttpResponseBadRequest(
            json.dumps({'status': 'error', 'message': message}))

    # Get the model
    m = get_model(*model_name.split('.'))

    # Then look up the object by pk
    try:
        obj = m.objects.get(pk=object_pk)
    except ObjectDoesNotExist:
        message = _('Object does not exist.')
        return HttpResponseNotFound(
            json.dumps({'status': 'error', 'message': message}))

    try:
        file_info = upload_imageattachment(request, obj)
    except FileTooLargeError as e:
        return HttpResponseBadRequest(
            json.dumps({'status': 'error', 'message': e.args[0]}))

    if isinstance(file_info, dict) and 'thumbnail_url' in file_info:
        return HttpResponse(
            json.dumps({'status': 'success', 'file': file_info}))

    message = _('Invalid or no image received.')
    return HttpResponseBadRequest(
        json.dumps({'status': 'error', 'message': message,
                    'errors': file_info}))
开发者ID:Acidburn0zzz,项目名称:kitsune,代码行数:34,代码来源:views.py


示例15: ajax

def ajax(request):
    """Query for a user matching a given email."""

    if "q" not in request.GET:
        raise http.Http404()

    data = {"status": 0, "message": ""}

    email = request.GET.get("q", "").strip()
    dev_only = request.GET.get("dev", "1")
    try:
        dev_only = int(dev_only)
    except ValueError:
        dev_only = 1
    dev_only = dev_only and settings.MARKETPLACE

    if not email:
        data.update(message=_("An email address is required."))
        return data

    user = UserProfile.objects.filter(email=email)
    if dev_only:
        user = user.exclude(read_dev_agreement=None)

    msg = _("A user with that email address does not exist.")
    msg_dev = _(
        "A user with that email address does not exist, or the user " "has not yet accepted the developer agreement."
    )

    if user:
        data.update(status=1, id=user[0].id, name=user[0].name)
    else:
        data["message"] = msg_dev if dev_only else msg

    return escape_all(data)
开发者ID:hardikj,项目名称:zamboni,代码行数:35,代码来源:views.py


示例16: description

 def description(self, category):
     """Description for the feed as a whole"""
     if category:
         # L10n: %s is a category name.
         return _(u'%s Add-ons') % category.name
     else:
         return _('Extensions')
开发者ID:ozten,项目名称:zamboni,代码行数:7,代码来源:feeds.py


示例17: clean_price

    def clean_price(self):
        price_value = self.cleaned_data.get('price')
        premium_type = self.cleaned_data.get('premium_type')
        if ((premium_type in amo.ADDON_PREMIUMS
                or premium_type == amo.ADDON_FREE_INAPP)
                and not price_value and not self.is_toggling()):
            raise_required()

        if not price_value and self.fields['price'].required is False:
            return None

        # Special case for a free app - in-app payments must be enabled.
        # Note: this isn't enforced for tier zero apps.
        if price_value == 'free':
            if self.cleaned_data.get('allow_inapp') != 'True':
                raise ValidationError(_('If app is Free, '
                                        'in-app payments must be enabled'))
            return price_value

        try:
            price = Price.objects.get(pk=price_value, active=True)
        except (ValueError, Price.DoesNotExist):
            raise ValidationError(_('Not a valid choice'))

        return price
开发者ID:MaxMillion,项目名称:zamboni,代码行数:25,代码来源:forms_payments.py


示例18: clean

    def clean(self):
        # If lng/lat were provided, make sure they point at a country somewhere...
        if self.cleaned_data.get('lat') is not None and self.cleaned_data.get('lng') is not None:
            # We only want to call reverse_geocode if some location data changed.
            if ('lat' in self.changed_data or 'lng' in self.changed_data or
                    'saveregion' in self.changed_data or 'savecity' in self.changed_data):
                self.instance.lat = self.cleaned_data['lat']
                self.instance.lng = self.cleaned_data['lng']
                self.instance.reverse_geocode()
                if not self.instance.geo_country:
                    error_msg = _('Location must be inside a country.')
                    self.errors['savecountry'] = self.error_class([error_msg])
                    del self.cleaned_data['savecountry']
                # If the user doesn't want their region/city saved, respect it.
                if not self.cleaned_data.get('saveregion'):
                    if not self.cleaned_data.get('savecity'):
                        self.instance.geo_region = None
                    else:
                        error_msg = _('Region must also be saved if city is saved.')
                        self.errors['saveregion'] = self.error_class([error_msg])

                if not self.cleaned_data.get('savecity'):
                    self.instance.geo_city = None
        else:
            self.errors['location'] = self.error_class([_('Search for your country on the map.')])
            self.errors['savecountry'] = self.error_class([_('Country cannot be empty.')])
            del self.cleaned_data['savecountry']

        return self.cleaned_data
开发者ID:buluma,项目名称:mozillians,代码行数:29,代码来源:forms.py


示例19: parse_xpi

def parse_xpi(xpi, addon=None, check=True):
    """Extract and parse an XPI."""
    # Extract to /tmp
    path = tempfile.mkdtemp()
    try:
        xpi = get_file(xpi)
        extract_xpi(xpi, path)
        xpi_info = Extractor.parse(path)
    except forms.ValidationError:
        raise
    except IOError as e:
        if len(e.args) < 2:
            errno, strerror = None, e[0]
        else:
            errno, strerror = e
        log.error('I/O error({0}): {1}'.format(errno, strerror))
        raise forms.ValidationError(_('Could not parse install.rdf.'))
    except Exception:
        log.error('XPI parse error', exc_info=True)
        raise forms.ValidationError(_('Could not parse install.rdf.'))
    finally:
        rm_local_tmp_dir(path)

    if check:
        return check_xpi_info(xpi_info, addon)
    else:
        return xpi_info
开发者ID:ujdhesa,项目名称:olympia,代码行数:27,代码来源:utils.py


示例20: account_settings

def account_settings(request):
    ctx = {}

    # Don't use `request.amo_user` because it's too cached.
    user = request.user
    if user.is_authenticated():
        amo_user = user.get_profile()
        form = forms.UserEditForm(request.POST or None, instance=amo_user)
        if request.method == 'POST':
            if form.is_valid():
                form.save()
                messages.success(request, _('Settings Updated.'))
                amo.log(amo.LOG.USER_EDITED)
                response = redirect('account.settings')
                # TODO: Detect when we're changing the user's locale and region
                # and bust on '/', bust on '/settings' for everything else.
                bust_fragments(response, '/')
                return response
            else:
                messages.form_errors(request)
        ctx = {'form': form, 'amouser': amo_user}
    else:
        if request.method == 'POST':
            messages.success(request, _('Settings Updated.'))

    return jingo.render(request, 'account/settings.html', ctx)
开发者ID:MaxDumont,项目名称:zamboni,代码行数:26,代码来源:views.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python tower._lazy函数代码示例发布时间:2022-05-27
下一篇:
Python utils.get_currtime函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap