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


Python statsd.incr函数代码示例

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


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

示例1: get_profile

    def get_profile(self):
        """Retrieve the Django UserProfile for this Person.

        This is full of hacks because all the Mozillians servers are throwing
        ObjectDoesNotExist errors (even in production) if we try a straight-up
        `User.objects.get(email=self.username)`. This method now exhaustively
        tries to get a User object from the database. If it doesn't find one,
        or finds one without a UserProfile, we make one on the spot, trying
        our best to fill things in sanely. FML.

        See: https://bugzilla.mozilla.org/show_bug.cgi?id=698699

        TODO: Remove this as soon as possible. It's insane.
        """
        user = (User.objects.filter(Q(email=self.username) | Q(username=self.username)))[:1]

        if user:
            # Yes, sometimes the User exists but the UserProfile doesn't.
            # See: https://bugzilla.mozilla.org/show_bug.cgi?id=699234
            try:
                profile = user[0].get_profile()
            except ObjectDoesNotExist, e:
                statsd.incr("user.errors.profile_doesnotexist")
                log.warning(e)

                profile = UserProfile.objects.create(user=user[0])
开发者ID:rik,项目名称:mozillians,代码行数:26,代码来源:__init__.py

示例2: handle_register

def handle_register(request, email_template=None, email_subject=None,
                    email_data=None):
    """Handle to help registration."""
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            form = try_send_email_with_form(
                RegistrationProfile.objects.create_inactive_user,
                form, 'email',
                form.cleaned_data['username'],
                form.cleaned_data['password'],
                form.cleaned_data['email'],
                locale=request.locale,
                email_template=email_template,
                email_subject=email_subject,
                email_data=email_data)
            if not form.is_valid():
                # Delete user if form is not valid, i.e. email was not sent.
                # This is in a POST request and so always pinned to master,
                # so there is no race condition.
                User.objects.filter(email=form.instance.email).delete()
            else:
                statsd.incr('user.register')
        return form
    return RegisterForm()
开发者ID:Curlified,项目名称:kitsune,代码行数:25,代码来源:utils.py

示例3: 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

示例4: creator_num_points

 def creator_num_points(self):
     try:
         return KarmaManager().count(
             'all', user=self.creator, type='points')
     except RedisError as e:
         statsd.incr('redis.errror')
         log.error('Redis connection error: %s' % e)
开发者ID:MiChrFri,项目名称:kitsune,代码行数:7,代码来源:models.py

示例5: watch_document

def watch_document(request, document_slug):
    """Start watching a document for edits."""
    document = get_object_or_404(
        Document, locale=request.LANGUAGE_CODE, slug=document_slug)
    EditDocumentEvent.notify(request.user, document)
    statsd.incr('wiki.watches.document')
    return HttpResponseRedirect(document.get_absolute_url())
开发者ID:atishrails,项目名称:kitsune,代码行数:7,代码来源:views.py

示例6: watch_approved

def watch_approved(request):
    """Start watching approved revisions in a locale."""
    if request.locale not in settings.SUMO_LANGUAGES:
        raise Http404
    ApproveRevisionInLocaleEvent.notify(request.user, locale=request.locale)
    statsd.incr('wiki.watches.approved')
    return HttpResponse()
开发者ID:fox2mike,项目名称:kitsune,代码行数:7,代码来源:views.py

示例7: submit_ticket

def submit_ticket(email, category, subject, body):
    """Submit a marketplace ticket to Zendesk.

    :arg email: user's email address
    :arg category: issue's category
    :arg subject: issue's subject
    :arg body: issue's description
    """
    # Create the Zendesk connection client.
    zendesk = get_zendesk()

    # Create the ticket
    new_ticket = {
        'ticket': {
            'requester_email': email,
            'subject': settings.ZENDESK_SUBJECT_PREFIX + subject,
            'description': body,
            'set_tags': category,
        }
    }
    try:
        ticket_url = zendesk.create_ticket(data=new_ticket)
        statsd.incr('questions.zendesk.success')
    except ZendeskError as e:
        log.error('Zendesk error: %s' % e.msg)
        statsd.incr('questions.zendesk.error')
        raise

    return ticket_url
开发者ID:GabiThume,项目名称:kitsune,代码行数:29,代码来源:marketplace.py

示例8: find_related_documents

def find_related_documents(doc):
    """
    Returns a QuerySet of related_docuemnts or of the
    parent's related_documents in the case of translations
    """
    if doc.locale == settings.WIKI_DEFAULT_LANGUAGE:
        return doc.related_documents.order_by('-related_to__in_common')[0:5]

    # Not English, so may need related docs which are
    # stored on the English version.
    try:
        redis = redis_client('default')
    except RedisError as e:
        # Problem with Redis. Log and return the related docs.
        statsd.incr('redis.errror')
        log.error('Redis error: %s' % e)
        return related_translated_documents(doc)

    doc_key = 'translated_doc_id:%s' % doc.id
    related_ids = redis.lrange(doc_key, 0, -1)
    if related_ids == ['0']:
        return Document.objects.get_empty_query_set()
    if related_ids:
        return Document.objects.filter(id__in=related_ids)

    related = related_translated_documents(doc)
    if not related:
        # Add '0' to prevent recalulation on a known empty set.
        redis.lpush(doc_key, 0)
    else:
        for r in related:
            redis.lpush(doc_key, r.id)
    # Cache expires in 2 hours.
    redis.expire(doc_key, 60 * 60 * 2)
    return related
开发者ID:Apokalyptica79,项目名称:kitsune,代码行数:35,代码来源:utils.py

示例9: _get_registered_user

def _get_registered_user(directory, request):
    """Checks the directory for a registered user.

    Function returns a tuple of registered and details.
    Registered is True if a user is found and False otherwise.
    If registered is True then details contains info about
    the known user.

    The statsd timer ``larper.sasl_bind_time`` allows IT to detect
    timeouts between ldap and https://browserid.org/verify. If this
    counter gets large, check DNS routes between slapd servers and
    browserid.org.

    The statsd counter
    ``browserid.unknown_error_checking_registered_user``
    allows IT to detect a problem with the backend auth system.
    """
    registered = False
    details = None
    try:
        (registered, details) = directory.registered_user()
        if registered:
            request.session['unique_id'] = details
        else:
            request.session['verified_email'] = details
    except Exception, e:
        # Look at syslogs on slapd hosts to investigate unknown issues
        messages.error(request,
                       _("We're Sorry, but Something Went Wrong!"))
        statsd.incr('browserid.unknown_error_checking_registered_user')
        log.error("Unknown error, clearing session assertion [%s]", e)
        store_assertion(request, None)
开发者ID:ahrokib,项目名称:mozillians,代码行数:32,代码来源:backend.py

示例10: new_thread

def new_thread(request, document_slug):
    """Start a new thread."""
    doc = get_document(document_slug, request)

    if request.method == "GET":
        form = NewThreadForm()
        return render(request, "kbforums/new_thread.html", {"form": form, "document": doc})

    form = NewThreadForm(request.POST)
    post_preview = None
    if form.is_valid():
        if "preview" in request.POST:
            thread = Thread(creator=request.user, title=form.cleaned_data["title"])
            post_preview = Post(thread=thread, creator=request.user, content=form.cleaned_data["content"])
        elif not _is_ratelimited(request):
            thread = doc.thread_set.create(creator=request.user, title=form.cleaned_data["title"])
            thread.save()
            statsd.incr("kbforums.thread")
            post = thread.new_post(creator=request.user, content=form.cleaned_data["content"])
            post.save()

            # Send notifications to forum watchers.
            NewThreadEvent(post).fire(exclude=post.creator)

            # Add notification automatically if needed.
            if Setting.get_for_user(request.user, "kbforums_watch_new_thread"):
                NewPostEvent.notify(request.user, thread)

            return HttpResponseRedirect(reverse("wiki.discuss.posts", args=[document_slug, thread.id]))

    return render(request, "kbforums/new_thread.html", {"form": form, "document": doc, "post_preview": post_preview})
开发者ID:chupahanks,项目名称:kitsune,代码行数:31,代码来源:views.py

示例11: sanitize_result

    def sanitize_result(self, result):
        """ Validates grader response `dict` to ensure the LMS can handle it.

        Type coercion for score and correct values, XML validation for msg
        value.

        The LMS is not forgiving if a grader response message contains invalid
        XML. To work around this we run the message through the same XML
        function used in the LMS, and if it raises any exceptions we replace
        this message informing students to notify course staff.

        """
        valid = {}
        try:
            # Santize score / correct
            valid["correct"] = bool(result["correct"])
            valid["score"] = float(result["score"])

            # Ensure response message contains valid XML. If it doesn't,
            # replace it with a message informing students to notify
            # course staff and log the error.
            try:
                etree.fromstring(result["msg"])
                valid["msg"] = result["msg"]
            except etree.XMLSyntaxError as e:
                log.error("Grader response message contains invalid XML: %s (%s)", result["msg"], e)
                valid["msg"] = "<div>Unable to display results. Please report this issue to course staff.</div>"
                statsd.incr("bux_grader_framework.invalid_grader_response")

        except Exception:
            raise InvalidGraderReply("Invalid grader response")

        return valid
开发者ID:abduld,项目名称:bux-grader-framework,代码行数:33,代码来源:xqueue.py

示例12: post_preview_async

def post_preview_async(request):
    """Ajax preview of posts."""
    statsd.incr('forums.preview')
    post = Post(author=request.user, content=request.POST.get('content', ''))
    post.author_post_count = 1
    return jingo.render(request, 'forums/includes/post_preview.html',
                        {'post_preview': post})
开发者ID:Curlified,项目名称:kitsune,代码行数:7,代码来源:views.py

示例13: _rebuild_kb_chunk

def _rebuild_kb_chunk(data):
    """Re-render a chunk of documents.

    Note: Don't use host components when making redirects to wiki pages; those
    redirects won't be auto-pruned when they're 404s.

    """
    log.info('Rebuilding %s documents.' % len(data))

    pin_this_thread()  # Stick to master.

    messages = []
    start = time.time()
    for pk in data:
        message = None
        try:
            document = Document.objects.get(pk=pk)

            # If we know a redirect link to be broken (i.e. if it looks like a
            # link to a document but the document isn't there), log an error:
            url = document.redirect_url()
            if (url and points_to_document_view(url) and
                    not document.redirect_document()):
                log.warn('Invalid redirect document: %d' % pk)

            html = document.parse_and_calculate_links()
            if document.html != html:
                # We are calling update here to so we only update the html
                # column instead of all of them. This bypasses post_save
                # signal handlers like the one that triggers reindexing.
                # See bug 797038 and bug 797352.
                Document.objects.filter(pk=pk).update(html=html)
                statsd.incr('wiki.rebuild_chunk.change')
            else:
                statsd.incr('wiki.rebuild_chunk.nochange')
        except Document.DoesNotExist:
            message = 'Missing document: %d' % pk
        except Revision.DoesNotExist:
            message = 'Missing revision for document: %d' % pk
        except ValidationError as e:
            message = 'ValidationError for %d: %s' % (pk, e.messages[0])
        except SlugCollision:
            message = 'SlugCollision: %d' % pk
        except TitleCollision:
            message = 'TitleCollision: %d' % pk

        if message:
            log.debug(message)
            messages.append(message)
    d = time.time() - start
    statsd.timing('wiki.rebuild_chunk', int(round(d * 1000)))

    if messages:
        subject = ('[%s] Exceptions raised in _rebuild_kb_chunk()' %
                   settings.PLATFORM_NAME)
        mail_admins(subject=subject, message='\n'.join(messages))
    if not transaction.get_connection().in_atomic_block:
        transaction.commit()

    unpin_this_thread()  # Not all tasks need to do use the master.
开发者ID:1234-,项目名称:kitsune,代码行数:60,代码来源:tasks.py

示例14: helpful_vote

def helpful_vote(request, document_slug):
    """Vote for Helpful/Not Helpful document"""
    revision = get_object_or_404(
        Revision, id=request.POST['revision_id'])

    if not revision.has_voted(request):
        ua = request.META.get('HTTP_USER_AGENT', '')[:1000]  # 1000 max_length
        vote = HelpfulVote(revision=revision, user_agent=ua)

        if 'helpful' in request.POST:
            vote.helpful = True
            message = _('Glad to hear it &mdash; thanks for the feedback!')
        else:
            message = _('Sorry to hear that. Try searching for solutions '
                        'below.')

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

        vote.save()
        statsd.incr('wiki.vote')
    else:
        message = _('You already voted on this Article.')

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

    return HttpResponseRedirect(revision.document.get_absolute_url())
开发者ID:jledbetter,项目名称:kitsune,代码行数:30,代码来源:views.py

示例15: new_thread

def new_thread(request, document_slug):
    """Start a new thread."""
    doc = get_document(document_slug, request)

    if request.method == 'GET':
        form = NewThreadForm()
        return jingo.render(request, 'kbforums/new_thread.html',
                            {'form': form, 'document': doc})

    form = NewThreadForm(request.POST)
    post_preview = None
    if form.is_valid():
        if 'preview' in request.POST:
            thread = Thread(creator=request.user,
                            title=form.cleaned_data['title'])
            post_preview = Post(thread=thread, creator=request.user,
                                content=form.cleaned_data['content'])
        else:
            thread = doc.thread_set.create(creator=request.user,
                                             title=form.cleaned_data['title'])
            thread.save()
            statsd.incr('kbforums.thread')
            post = thread.new_post(creator=request.user,
                                   content=form.cleaned_data['content'])
            post.save()

            # Send notifications to forum watchers.
            NewThreadEvent(post).fire(exclude=post.creator)

            return HttpResponseRedirect(
                reverse('wiki.discuss.posts', args=[document_slug, thread.id]))

    return jingo.render(request, 'kbforums/new_thread.html',
                        {'form': form, 'document': doc,
                         'post_preview': post_preview})
开发者ID:chengwang,项目名称:kitsune,代码行数:35,代码来源:views.py


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