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


Python response.json_success函数代码示例

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


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

示例1: api_basecamp_webhook

def api_basecamp_webhook(request: HttpRequest, user_profile: UserProfile,
                         payload: Dict[str, Any]=REQ(argument_type='body')) -> HttpResponse:
    event = get_event_type(payload)

    if event not in SUPPORT_EVENTS:
        logging.warning("Basecamp {} event is not supported".format(event))
        return json_success()

    subject = get_project_name(payload)
    if event.startswith('document_'):
        body = get_document_body(event, payload)
    elif event.startswith('question_answer_'):
        body = get_questions_answer_body(event, payload)
    elif event.startswith('question_'):
        body = get_questions_body(event, payload)
    elif event.startswith('message_'):
        body = get_message_body(event, payload)
    elif event.startswith('todolist_'):
        body = get_todo_list_body(event, payload)
    elif event.startswith('todo_'):
        body = get_todo_body(event, payload)
    elif event.startswith('comment_'):
        body = get_comment_body(event, payload)
    else:
        logging.warning("Basecamp handling of {} event is not implemented".format(event))
        return json_success()

    check_send_webhook_message(request, user_profile, subject, body)
    return json_success()
开发者ID:gnprice,项目名称:zulip,代码行数:29,代码来源:view.py

示例2: api_gogs_webhook

def api_gogs_webhook(request: HttpRequest, user_profile: UserProfile,
                     payload: Dict[str, Any]=REQ(argument_type='body'),
                     stream: Text=REQ(default='commits'),
                     branches: Optional[Text]=REQ(default=None)) -> HttpResponse:

    repo = payload['repository']['name']
    event = request.META['HTTP_X_GOGS_EVENT']
    if event == 'push':
        branch = payload['ref'].replace('refs/heads/', '')
        if branches is not None and branches.find(branch) == -1:
            return json_success()
        body = format_push_event(payload)
        topic = SUBJECT_WITH_BRANCH_TEMPLATE.format(
            repo=repo,
            branch=branch
        )
    elif event == 'create':
        body = format_new_branch_event(payload)
        topic = SUBJECT_WITH_BRANCH_TEMPLATE.format(
            repo=repo,
            branch=payload['ref']
        )
    elif event == 'pull_request':
        body = format_pull_request_event(payload)
        topic = SUBJECT_WITH_PR_OR_ISSUE_INFO_TEMPLATE.format(
            repo=repo,
            type='PR',
            id=payload['pull_request']['id'],
            title=payload['pull_request']['title']
        )
    else:
        return json_error(_('Invalid event "{}" in request headers').format(event))

    check_send_stream_message(user_profile, request.client, stream, topic, body)
    return json_success()
开发者ID:joydeep1701,项目名称:zulip,代码行数:35,代码来源:view.py

示例3: api_bitbucket_webhook

def api_bitbucket_webhook(request, user_profile, payload=REQ(validator=check_dict([])),
                          stream=REQ(default='commits'), branches=REQ(default=None)):
    # type: (HttpRequest, UserProfile, Mapping[Text, Any], Text, Optional[Text]) -> HttpResponse
    repository = payload['repository']

    commits = [
        {
            'name': payload.get('user'),
            'sha': commit.get('raw_node'),
            'message': commit.get('message'),
            'url': u'{}{}commits/{}'.format(
                payload.get('canon_url'),
                repository.get('absolute_url'),
                commit.get('raw_node'))
        }
        for commit in payload['commits']
    ]

    if len(commits) == 0:
        # Bitbucket doesn't give us enough information to really give
        # a useful message :/
        subject = repository['name']
        content = (u"%s [force pushed](%s)"
                   % (payload['user'],
                      payload['canon_url'] + repository['absolute_url']))
    else:
        branch = payload['commits'][-1]['branch']
        if branches is not None and branches.find(branch) == -1:
            return json_success()
        content = get_push_commits_event_message(payload['user'], None, branch, commits)
        subject = SUBJECT_WITH_BRANCH_TEMPLATE.format(repo=repository['name'], branch=branch)

    check_send_message(user_profile, get_client("ZulipBitBucketWebhook"), "stream",
                       [stream], subject, content)
    return json_success()
开发者ID:JamesLinus,项目名称:zulip,代码行数:35,代码来源:view.py

示例4: json_report_error

def json_report_error(request, user_profile, message=REQ(), stacktrace=REQ(),
                      ui_message=REQ(validator=check_bool), user_agent=REQ(),
                      href=REQ(), log=REQ(),
                      more_info=REQ(validator=check_dict([]), default=None)):
    # type: (HttpRequest, UserProfile, text_type, text_type, bool, text_type, text_type, text_type, Dict[str, Any]) -> HttpResponse
    if not settings.ERROR_REPORTING:
        return json_success()

    if js_source_map:
        stacktrace = js_source_map.annotate_stacktrace(stacktrace)

    try:
        version = subprocess.check_output(["git", "log", "HEAD^..HEAD", "--oneline"], universal_newlines=True)
    except Exception:
        version = None

    queue_json_publish('error_reports', dict(
        type = "browser",
        report = dict(
            user_email = user_profile.email,
            user_full_name = user_profile.full_name,
            user_visible = ui_message,
            server_path = settings.DEPLOY_ROOT,
            version = version,
            user_agent = user_agent,
            href = href,
            message = message,
            stacktrace = stacktrace,
            log = log,
            more_info = more_info,
        )
    ), lambda x: None)

    return json_success()
开发者ID:150vb,项目名称:zulip,代码行数:34,代码来源:report.py

示例5: api_gogs_webhook

def api_gogs_webhook(request: HttpRequest, user_profile: UserProfile,
                     payload: Dict[str, Any]=REQ(argument_type='body'),
                     branches: Optional[str]=REQ(default=None)) -> HttpResponse:

    repo = payload['repository']['name']
    event = validate_extract_webhook_http_header(request, 'X_GOGS_EVENT', 'Gogs')
    if event == 'push':
        branch = payload['ref'].replace('refs/heads/', '')
        if branches is not None and branches.find(branch) == -1:
            return json_success()
        body = format_push_event(payload)
        topic = SUBJECT_WITH_BRANCH_TEMPLATE.format(
            repo=repo,
            branch=branch
        )
    elif event == 'create':
        body = format_new_branch_event(payload)
        topic = SUBJECT_WITH_BRANCH_TEMPLATE.format(
            repo=repo,
            branch=payload['ref']
        )
    elif event == 'pull_request':
        body = format_pull_request_event(payload)
        topic = SUBJECT_WITH_PR_OR_ISSUE_INFO_TEMPLATE.format(
            repo=repo,
            type='PR',
            id=payload['pull_request']['id'],
            title=payload['pull_request']['title']
        )
    else:
        raise UnexpectedWebhookEventType('Gogs', event)

    check_send_webhook_message(request, user_profile, topic, body)
    return json_success()
开发者ID:phansen01,项目名称:zulip,代码行数:34,代码来源:view.py

示例6: api_travis_webhook

def api_travis_webhook(request: HttpRequest, user_profile: UserProfile,
                       ignore_pull_requests: bool = REQ(validator=check_bool, default=True),
                       message: Dict[str, str]=REQ('payload', validator=check_dict([
                           ('author_name', check_string),
                           ('status_message', check_string),
                           ('compare_url', check_string),
                       ]))) -> HttpResponse:

    message_status = message['status_message']
    if ignore_pull_requests and message['type'] == 'pull_request':
        return json_success()

    if message_status in GOOD_STATUSES:
        emoji = ':thumbs_up:'
    elif message_status in BAD_STATUSES:
        emoji = ':thumbs_down:'
    else:
        emoji = "(No emoji specified for status '{}'.)".format(message_status)

    body = MESSAGE_TEMPLATE.format(
        message['author_name'],
        message_status,
        emoji,
        message['compare_url'],
        message['build_url']
    )
    topic = 'builds'

    check_send_webhook_message(request, user_profile, topic, body)
    return json_success()
开发者ID:BakerWang,项目名称:zulip,代码行数:30,代码来源:view.py

示例7: api_beanstalk_webhook

def api_beanstalk_webhook(request, user_profile,
                          payload=REQ(validator=check_dict([])),
                          branches=REQ(default=None)):
    # type: (HttpRequest, UserProfile, Dict[str, Any], Optional[Text]) -> HttpResponse
    # Beanstalk supports both SVN and git repositories
    # We distinguish between the two by checking for a
    # 'uri' key that is only present for git repos
    git_repo = 'uri' in payload
    if git_repo:
        if branches is not None and branches.find(payload['branch']) == -1:
            return json_success()
        # To get a linkable url,
        for commit in payload['commits']:
            commit['author'] = {'username': commit['author']['name']}

        subject, content = build_message_from_gitlog(user_profile, payload['repository']['name'],
                                                     payload['ref'], payload['commits'],
                                                     payload['before'], payload['after'],
                                                     payload['repository']['url'],
                                                     payload['pusher_name'])
    else:
        author = payload.get('author_full_name')
        url = payload.get('changeset_url')
        revision = payload.get('revision')
        (short_commit_msg, _, _) = payload.get('message').partition("\n")

        subject = "svn r%s" % (revision,)
        content = "%s pushed [revision %s](%s):\n\n> %s" % (author, revision, url, short_commit_msg)

    check_send_message(user_profile, get_client("ZulipBeanstalkWebhook"), "stream",
                       ["commits"], subject, content)
    return json_success()
开发者ID:christi3k,项目名称:zulip,代码行数:32,代码来源:view.py

示例8: api_teamcity_webhook

def api_teamcity_webhook(request, user_profile, payload=REQ(argument_type='body'),
                         stream=REQ(default='teamcity')):
    # type: (HttpRequest, UserProfile, Dict[str, Any], str) -> HttpResponse
    message = payload['build']

    build_name = message['buildFullName']
    build_url = message['buildStatusUrl']
    changes_url = build_url + '&tab=buildChangesDiv'
    build_number = message['buildNumber']
    build_result = message['buildResult']
    build_result_delta = message['buildResultDelta']
    build_status = message['buildStatus']

    if build_result == 'success':
        if build_result_delta == 'fixed':
            status = 'has been fixed! :thumbsup:'
        else:
            status = 'was successful! :thumbsup:'
    elif build_result == 'failure':
        if build_result_delta == 'broken':
            status = 'is broken with status %s! :thumbsdown:' % (build_status,)
        else:
            status = 'is still broken with status %s! :thumbsdown:' % (build_status,)
    elif build_result == 'running':
        status = 'has started.'
    else:
        status = '(has no message specified for status %s)' % (build_status,)

    template = (
        u'%s build %s %s\n'
        u'Details: [changes](%s), [build log](%s)')

    body = template % (build_name, build_number, status, changes_url, build_url)
    topic = build_name

    # Check if this is a personal build, and if so try to private message the user who triggered it.
    if get_teamcity_property_value(message['teamcityProperties'], 'env.BUILD_IS_PERSONAL') == 'true':
        # The triggeredBy field gives us the teamcity user full name, and the "teamcity.build.triggeredBy.username"
        # property gives us the teamcity username. Let's try finding the user email from both.
        teamcity_fullname = message['triggeredBy'].split(';')[0]
        teamcity_user = guess_zulip_user_from_teamcity(teamcity_fullname, user_profile.realm)

        if teamcity_user is None:
            teamcity_shortname = get_teamcity_property_value(message['teamcityProperties'],
                                                             'teamcity.build.triggeredBy.username')
            if teamcity_shortname is not None:
                teamcity_user = guess_zulip_user_from_teamcity(teamcity_shortname, user_profile.realm)

        if teamcity_user is None:
            # We can't figure out who started this build - there's nothing we can do here.
            logging.info("Teamcity webhook couldn't find a matching Zulip user for Teamcity user '%s' or '%s'" % (
                teamcity_fullname, teamcity_shortname))
            return json_success()

        body = "Your personal build of " + body
        check_send_message(user_profile, request.client, 'private', [teamcity_user.email], topic, body)
        return json_success()

    check_send_message(user_profile, request.client, 'stream', [stream], topic, body)
    return json_success()
开发者ID:JamesLinus,项目名称:zulip,代码行数:60,代码来源:view.py

示例9: api_jira_webhook

def api_jira_webhook(request: HttpRequest, user_profile: UserProfile,
                     payload: Dict[str, Any]=REQ(argument_type='body')) -> HttpResponse:

    event = get_event_type(payload)
    if event == 'jira:issue_created':
        subject = get_issue_subject(payload)
        content = handle_created_issue_event(payload)
    elif event == 'jira:issue_deleted':
        subject = get_issue_subject(payload)
        content = handle_deleted_issue_event(payload)
    elif event == 'jira:issue_updated':
        subject = get_issue_subject(payload)
        content = handle_updated_issue_event(payload, user_profile)
    elif event == 'comment_created':
        subject = get_issue_subject(payload)
        content = handle_updated_issue_event(payload, user_profile)
    elif event in IGNORED_EVENTS:
        return json_success()
    else:
        raise UnexpectedWebhookEventType('Jira', event)

    check_send_webhook_message(request, user_profile,
                               subject, content,
                               unquote_url_parameters=True)
    return json_success()
开发者ID:BakerWang,项目名称:zulip,代码行数:25,代码来源:view.py

示例10: api_jira_webhook

def api_jira_webhook(request, user_profile,
                     payload=REQ(argument_type='body'),
                     stream=REQ(default='jira')):
    # type: (HttpRequest, UserProfile, Dict[str, Any], Text) -> HttpResponse

    event = get_event_type(payload)
    if event == 'jira:issue_created':
        subject = get_issue_subject(payload)
        content = handle_created_issue_event(payload)
    elif event == 'jira:issue_deleted':
        subject = get_issue_subject(payload)
        content = handle_deleted_issue_event(payload)
    elif event == 'jira:issue_updated':
        subject = get_issue_subject(payload)
        content = handle_updated_issue_event(payload, user_profile)
    elif event in IGNORED_EVENTS:
        return json_success()
    else:
        if event is None:
            if not settings.TEST_SUITE:
                message = u"Got JIRA event with None event type: {}".format(payload)
                logging.warning(message)
            return json_error(_("Event is not given by JIRA"))
        else:
            if not settings.TEST_SUITE:
                logging.warning("Got JIRA event type we don't support: {}".format(event))
            return json_success()

    check_send_stream_message(user_profile, request.client, stream, subject, content)
    return json_success()
开发者ID:brockwhittaker,项目名称:zulip,代码行数:30,代码来源:view.py

示例11: api_bitbucket2_webhook

def api_bitbucket2_webhook(request: HttpRequest, user_profile: UserProfile,
                           payload: Dict[str, Any]=REQ(argument_type='body'),
                           branches: Optional[str]=REQ(default=None),
                           user_specified_topic: Optional[str]=REQ("topic", default=None)) -> HttpResponse:
    type = get_type(request, payload)
    if type == 'push':
        # ignore push events with no changes
        if not payload['push']['changes']:
            return json_success()
        branch = get_branch_name_for_push_event(payload)
        if branch and branches:
            if branches.find(branch) == -1:
                return json_success()

    subject = get_subject_based_on_type(payload, type)
    body_function = get_body_based_on_type(type)
    if 'include_title' in signature(body_function).parameters:
        body = body_function(
            payload,
            include_title=user_specified_topic is not None
        )
    else:
        body = body_function(payload)

    if type != 'push':
        check_send_webhook_message(request, user_profile, subject, body)
    else:
        for b, s in zip(body, subject):
            check_send_webhook_message(request, user_profile, s, b)

    return json_success()
开发者ID:brainwane,项目名称:zulip,代码行数:31,代码来源:view.py

示例12: report_error

def report_error(request: HttpRequest, user_profile: UserProfile, message: str=REQ(),
                 stacktrace: str=REQ(), ui_message: bool=REQ(validator=check_bool),
                 user_agent: str=REQ(), href: str=REQ(), log: str=REQ(),
                 more_info: Optional[Dict[str, Any]]=REQ(validator=check_dict([]), default=None)
                 ) -> HttpResponse:
    """Accepts an error report and stores in a queue for processing.  The
    actual error reports are later handled by do_report_error (below)"""
    if not settings.BROWSER_ERROR_REPORTING:
        return json_success()
    if more_info is None:
        more_info = {}

    js_source_map = get_js_source_map()
    if js_source_map:
        stacktrace = js_source_map.annotate_stacktrace(stacktrace)

    try:
        version = subprocess.check_output(["git", "log", "HEAD^..HEAD", "--oneline"],
                                          universal_newlines=True)  # type: Optional[str]
    except Exception:
        version = None

    # Get the IP address of the request
    remote_ip = request.META.get('HTTP_X_REAL_IP')
    if remote_ip is None:
        remote_ip = request.META['REMOTE_ADDR']

    # For the privacy of our users, we remove any actual text content
    # in draft_content (from drafts rendering exceptions).  See the
    # comment on privacy_clean_markdown for more details.
    if more_info.get('draft_content'):
        more_info['draft_content'] = privacy_clean_markdown(more_info['draft_content'])

    if user_profile.is_authenticated:
        email = user_profile.delivery_email
        full_name = user_profile.full_name
    else:
        email = "[email protected]"
        full_name = "Anonymous User"

    queue_json_publish('error_reports', dict(
        type = "browser",
        report = dict(
            host = request.get_host().split(":")[0],
            ip_address = remote_ip,
            user_email = email,
            user_full_name = full_name,
            user_visible = ui_message,
            server_path = settings.DEPLOY_ROOT,
            version = version,
            user_agent = user_agent,
            href = href,
            message = message,
            stacktrace = stacktrace,
            log = log,
            more_info = more_info,
        )
    ))

    return json_success()
开发者ID:akashnimare,项目名称:zulip,代码行数:60,代码来源:report.py

示例13: api_zapier_webhook

def api_zapier_webhook(request: HttpRequest, user_profile: UserProfile,
                       payload: Dict[str, Any]=REQ(argument_type='body')) -> HttpResponse:
    if payload.get('type') == 'auth':
        # The bot's details are used by our Zapier app to format a connection
        # label for users to be able to distinguish between different Zulip
        # bots and API keys in their UI
        return json_success({
            'full_name': user_profile.full_name,
            'email': user_profile.email,
            'id': user_profile.id
        })

    topic = payload.get('topic')
    content = payload.get('content')

    if topic is None:
        topic = payload.get('subject')  # Backwards-compatibility
        if topic is None:
            return json_error(_("Topic can't be empty"))

    if content is None:
        return json_error(_("Content can't be empty"))

    check_send_webhook_message(request, user_profile, topic, content)
    return json_success()
开发者ID:jdherg,项目名称:zulip,代码行数:25,代码来源:view.py

示例14: api_freshdesk_webhook

def api_freshdesk_webhook(request: HttpRequest, user_profile: UserProfile,
                          payload: Dict[str, Any]=REQ(argument_type='body')) -> HttpResponse:
    ticket_data = payload["freshdesk_webhook"]

    required_keys = [
        "triggered_event", "ticket_id", "ticket_url", "ticket_type",
        "ticket_subject", "ticket_description", "ticket_status",
        "ticket_priority", "requester_name", "requester_email",
    ]

    for key in required_keys:
        if ticket_data.get(key) is None:
            logging.warning("Freshdesk webhook error. Payload was:")
            logging.warning(request.body)
            return json_error(_("Missing key %s in JSON") % (key,))

    ticket = TicketDict(ticket_data)

    subject = "#%s: %s" % (ticket.id, ticket.subject)
    event_info = parse_freshdesk_event(ticket.triggered_event)

    if event_info[1] == "created":
        content = format_freshdesk_ticket_creation_message(ticket)
    elif event_info[0] == "note_type":
        content = format_freshdesk_note_message(ticket, event_info)
    elif event_info[0] in ("status", "priority"):
        content = format_freshdesk_property_change_message(ticket, event_info)
    else:
        # Not an event we know handle; do nothing.
        return json_success()

    check_send_webhook_message(request, user_profile, subject, content)
    return json_success()
开发者ID:BakerWang,项目名称:zulip,代码行数:33,代码来源:view.py

示例15: api_travis_webhook

def api_travis_webhook(request, user_profile, client,
                       stream=REQ(default='travis'),
                       topic=REQ(default=None),
                       ignore_pull_requests=REQ(validator=check_bool, default=True),
                       message=REQ('payload', validator=check_dict([
                           ('author_name', check_string),
                           ('status_message', check_string),
                           ('compare_url', check_string),
                       ]))):
    # type: (HttpRequest, UserProfile, Client, str, str, str, Dict[str, str]) -> HttpResponse

    message_status = message['status_message']
    if ignore_pull_requests and message['type'] == 'pull_request':
        return json_success()

    if message_status in GOOD_STATUSES:
        emoji = ':thumbsup:'
    elif message_status in BAD_STATUSES:
        emoji = ':thumbsdown:'
    else:
        emoji = "(No emoji specified for status '{}'.)".format(message_status)

    body = MESSAGE_TEMPLATE.format(
        message['author_name'],
        message_status,
        emoji,
        message['compare_url'],
        message['build_url']
    )

    check_send_message(user_profile, client, 'stream', [stream], topic, body)
    return json_success()
开发者ID:aakash-cr7,项目名称:zulip,代码行数:32,代码来源:view.py


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