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

Python http.safe_urlopen函数代码示例

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

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



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

示例1: process_service_hook

def process_service_hook(servicehook_id, event, **kwargs):
    from sentry import tsdb
    from sentry.models import ServiceHook

    try:
        servicehook = ServiceHook.objects.get(id=servicehook_id)
    except ServiceHook.DoesNotExist:
        return

    tsdb.incr(tsdb.models.servicehook_fired, servicehook.id)

    if servicehook.version == 0:
        payload = get_payload_v0(event)
    else:
        raise NotImplementedError

    body = json.dumps(payload)

    headers = {
        'Content-Type': 'application/json',
        'X-ServiceHook-Timestamp': six.text_type(int(time())),
        'X-ServiceHook-GUID': servicehook.guid,
        'X-ServiceHook-Signature': servicehook.build_signature(body),
    }

    safe_urlopen(
        url=servicehook.url,
        data=body,
        headers=headers,
        timeout=5,
        verify_ssl=False,
    )
开发者ID:alexandrul,项目名称:sentry,代码行数:32,代码来源:servicehooks.py


示例2: process_resource_change

def process_resource_change(action, sender, instance_id, *args, **kwargs):
    model = None
    name = None

    # Previous method signature.
    if inspect.isclass(sender):
        model = sender
    else:
        model = TYPES[sender]

    name = RESOURCE_RENAMES.get(model.__name__, model.__name__.lower())

    # We may run into a race condition where this task executes before the
    # transaction that creates the Group has committed.
    try:
        instance = model.objects.get(id=instance_id)
    except model.DoesNotExist as e:
        # Explicitly requeue the task, so we don't report this to Sentry until
        # we hit the max number of retries.
        return current.retry(exc=e)

    event = '{}.{}'.format(name, action)

    if event not in ALLOWED_EVENTS:
        return

    project = None

    if isinstance(instance, Group):
        project = instance.project

    if not project:
        return

    servicehooks = ServiceHook.objects.filter(
        project_id=project.id,
    )

    for servicehook in filter(lambda s: event in s.events, servicehooks):
        # For now, these ``post_save`` callbacks are only valid for service
        # hooks created by a Sentry App.
        if not servicehook.created_by_sentry_app:
            continue

        request_data = AppPlatformEvent(
            resource=name,
            action=action,
            install=SentryAppInstallation.objects.get(id=servicehook.actor_id),
            data=serialize(instance),
        )

        safe_urlopen(
            url=servicehook.url,
            data=request_data.body,
            headers=request_data.headers,
            timeout=5,
        )
开发者ID:Kayle009,项目名称:sentry,代码行数:57,代码来源:servicehooks.py


示例3: notify_users

    def notify_users(self, group, event, **kwargs):
        project = group.project

        body = 'Sentry [{0}] {1}: {2}'.format(
            project.name.encode('utf-8'),
            event.get_level_display().upper().encode('utf-8'),
            event.error().encode('utf-8').splitlines()[0]
        )
        body = body[:MAX_SMS_LENGTH]

        account_sid = self.get_option('account_sid', project)
        auth_token = self.get_option('auth_token', project)
        sms_from = clean_phone(self.get_option('sms_from', project))
        endpoint = twilio_sms_endpoint.format(account_sid)

        sms_to = self.get_option('sms_to', project)
        if not sms_to:
            return
        sms_to = split_sms_to(sms_to)

        headers = {
            'Authorization': basic_auth(account_sid, auth_token),
        }

        errors = []

        for phone in sms_to:
            if not phone:
                continue
            try:
                phone = clean_phone(phone)
                http.safe_urlopen(
                    endpoint,
                    method='POST',
                    headers=headers,
                    data={
                        'From': sms_from,
                        'To': phone,
                        'Body': body,
                    },
                ).raise_for_status()
            except Exception as e:
                errors.append(e)

        if errors:
            if len(errors) == 1:
                raise errors[0]

            # TODO: multi-exception
            raise Exception(errors)
开发者ID:mattrobenolt,项目名称:sentry-twilio,代码行数:50,代码来源:models.py


示例4: _make_request

    def _make_request(self):
        req = safe_urlopen(
            url=self._build_url(),
            headers=self._build_headers(),
            method='POST',
            data=self.body,
        )

        try:
            body = safe_urlread(req)
            response = json.loads(body)
        except Exception:
            logger.info(
                'issue-link-requester.error',
                extra={
                    'sentry_app': self.sentry_app.slug,
                    'install': self.install.uuid,
                    'project': self.group.project.slug,
                    'group': self.group.id,
                    'uri': self.uri,
                }
            )
            response = {}

        if not self._validate_response(response):
            raise APIError()

        return response
开发者ID:getsentry,项目名称:sentry,代码行数:28,代码来源:issue_link_requester.py


示例5: send_webhook

 def send_webhook(self, url, data):
     return safe_urlopen(
         url=url,
         data=data,
         timeout=self.timeout,
         user_agent=self.user_agent,
     )
开发者ID:kyanny,项目名称:sentry-webhooks,代码行数:7,代码来源:plugin.py


示例6: send_webhook

 def send_webhook(self, url, payload):
     return safe_urlopen(
         url=url,
         json=payload,
         timeout=self.timeout,
         verify_ssl=False,
     )
开发者ID:280185386,项目名称:sentry,代码行数:7,代码来源:plugin.py


示例7: github_request

    def github_request(self, request, url, **kwargs):
        """
        Make a GitHub request on behalf of the logged in user. Return JSON
        response on success or raise forms.ValidationError on any exception
        """
        auth = self.get_auth_for_user(user=request.user)
        if auth is None:
            raise forms.ValidationError(_("You have not yet associated GitHub with your account."))

        headers = kwargs.pop("headers", None) or {}
        headers["Authorization"] = "token %s" % auth.tokens["access_token"]
        try:
            req = safe_urlopen(url, headers=headers, **kwargs)
            body = safe_urlread(req)
        except requests.RequestException as e:
            msg = unicode(e)
            raise forms.ValidationError(_("Error communicating with GitHub: %s") % (msg,))

        try:
            json_resp = json.loads(body)
        except ValueError as e:
            msg = unicode(e)
            raise forms.ValidationError(_("Error communicating with GitHub: %s") % (msg,))

        if req.status_code > 399:
            raise forms.ValidationError(json_resp["message"])

        return json_resp
开发者ID:imankulov,项目名称:sentry-github,代码行数:28,代码来源:plugin.py


示例8: _make_request

    def _make_request(self):
        try:
            body = safe_urlread(
                safe_urlopen(
                    url=self._build_url(),
                    headers=self._build_headers(),
                )
            )

            response = json.loads(body)
        except Exception as e:
            logger.info(
                'select-requester.error',
                extra={
                    'sentry_app': self.sentry_app.slug,
                    'install': self.install.uuid,
                    'project': self.project and self.project.slug,
                    'uri': self.uri,
                    'error_message': e.message,
                }
            )
            response = {}

        if not self._validate_response(response):
            raise APIError()

        return self._format_response(response)
开发者ID:getsentry,项目名称:sentry,代码行数:27,代码来源:select_requester.py


示例9: notify_users

    def notify_users(self, group, event, fail_silently=False):
        if not self.is_configured(group.project):
            return

        api_key = self.get_option('api_key', group.project)
        recipients = self.get_option('recipients', group.project)
        alert_url = self.get_option('alert_url', group.project)

        message = getattr(group, 'message_short', group.message).encode('utf-8')

        payload = {
           'apiKey': api_key,
           'message': message,
           'source': 'Sentry',
           'details': self.get_group_data(group, event)
        }

        if recipients:
            payload['recipients'] = recipients

        req = http.safe_urlopen(alert_url, json=payload)
        resp = req.json()

        if resp.get('status') != 'successful':
            raise Exception('Unsuccessful response from OpsGenie: %s' % resp)
开发者ID:zsjohny,项目名称:sentry-opsgenie,代码行数:25,代码来源:plugin.py


示例10: dispatch

    def dispatch(self, request, helper):
        access_token = helper.fetch_state('data')['access_token']

        req = safe_urlopen('{0}?{1}&alt=json'.format(
            USER_DETAILS_ENDPOINT,
            urlencode({
                'access_token': access_token,
            })
        ))
        body = safe_urlread(req)
        data = json.loads(body)

        if not data.get('data'):
            logger.error('Invalid response: %s' % body)
            return helper.error(ERR_INVALID_RESPONSE)

        if not data.get('data').get('email'):
            logger.error('Invalid response: %s' % body)
            return helper.error(ERR_INVALID_RESPONSE)

        domain = extract_domain(data.get('data').get('email'))

        if domain in DOMAIN_BLOCKLIST:
            return helper.error(ERR_INVALID_DOMAIN % (domain,))

        if self.domain and self.domain != domain:
            return helper.error(ERR_INVALID_DOMAIN % (domain,))

        helper.bind_state('domain', domain)
        helper.bind_state('user', data.get('data'))

        return helper.next_step()
开发者ID:dieswaytoofast,项目名称:sentry-auth-google,代码行数:32,代码来源:views.py


示例11: refresh_identity

    def refresh_identity(self, auth_identity):
        refresh_token = auth_identity.data.get("refresh_token")

        if not refresh_token:
            raise IdentityNotValid("Missing refresh token")

        data = self.get_refresh_token_params(refresh_token=refresh_token)
        req = safe_urlopen(self.get_refresh_token_url(), data=data)

        try:
            body = safe_urlread(req)
            payload = json.loads(body)
        except Exception:
            payload = {}

        error = payload.get("error", "unknown_error")
        error_description = payload.get("error_description", "no description available")

        formatted_error = "HTTP {} ({}): {}".format(req.status_code, error, error_description)

        if req.status_code == 401:
            raise IdentityNotValid(formatted_error)

        if req.status_code == 400:
            # this may not be common, but at the very least Google will return
            # an invalid grant when a user is suspended
            if error == "invalid_grant":
                raise IdentityNotValid(formatted_error)

        if req.status_code != 200:
            raise Exception(formatted_error)

        auth_identity.data.update(self.get_oauth_data(payload))
        auth_identity.update(data=auth_identity.data)
开发者ID:AyrtonRicardo,项目名称:sentry,代码行数:34,代码来源:oauth2.py


示例12: exchange_token

 def exchange_token(self, request, pipeline, code):
     # TODO: this needs the auth yet
     data = self.get_token_params(
         code=code,
         redirect_uri=absolute_uri(pipeline.redirect_url()),
     )
     verify_ssl = pipeline.config.get('verify_ssl', True)
     try:
         req = safe_urlopen(self.access_token_url, data=data, verify_ssl=verify_ssl)
         body = safe_urlread(req)
         if req.headers.get('Content-Type', '').startswith('application/x-www-form-urlencoded'):
             return dict(parse_qsl(body))
         return json.loads(body)
     except SSLError:
         logger.info('identity.oauth2.ssl-error', extra={
             'url': self.access_token_url,
             'verify_ssl': verify_ssl,
         })
         url = self.access_token_url
         return {
             'error': 'Could not verify SSL certificate',
             'error_description': u'Ensure that {} has a valid SSL certificate'.format(url)
         }
     except JSONDecodeError:
         logger.info('identity.oauth2.json-error', extra={
             'url': self.access_token_url,
         })
         return {
             'error': 'Could not decode a JSON Response',
             'error_description': u'We were not able to parse a JSON response, please try again.'
         }
开发者ID:Kayle009,项目名称:sentry,代码行数:31,代码来源:oauth2.py


示例13: exchange_token

    def exchange_token(self, request, helper, code):
        # TODO: this needs the auth yet
        data = self.get_token_params(code=code, redirect_uri=absolute_uri(helper.get_redirect_url()))
        req = safe_urlopen(self.access_token_url, data=data)
        body = safe_urlread(req)

        return json.loads(body)
开发者ID:Juraldinio,项目名称:sentry,代码行数:7,代码来源:oauth2.py


示例14: send_webhook

 def send_webhook(self, url, data):
     return safe_urlopen(
         url=url,
         data=data,
         timeout=self.timeout,
         user_agent=self.user_agent,
         headers=(('Accept-Encoding', 'gzip'), ('Content-type', 'application/json')),
     )
开发者ID:getsentry,项目名称:sentry-webhooks,代码行数:8,代码来源:plugin.py


示例15: exchange_token

 def exchange_token(self, request, helper, code):
     # TODO: this needs the auth yet
     data = self.get_token_params(code=code, redirect_uri=absolute_uri(helper.get_redirect_url()))
     req = safe_urlopen(self.access_token_url, data=data)
     body = safe_urlread(req)
     if req.headers["Content-Type"].startswith("application/x-www-form-urlencoded"):
         return dict(parse_qsl(body))
     return json.loads(body)
开发者ID:AyrtonRicardo,项目名称:sentry,代码行数:8,代码来源:oauth2.py


示例16: send_request

def send_request(servicehook, payload, verify_ssl=None):
    from sentry import tsdb
    tsdb.incr(tsdb.models.servicehook_fired, servicehook.id)

    headers = {
        'Content-Type': 'application/json',
        'X-ServiceHook-Timestamp': six.text_type(int(time())),
        'X-ServiceHook-GUID': servicehook.guid,
        'X-ServiceHook-Signature': servicehook.build_signature(json.dumps(payload)),
    }

    safe_urlopen(
        url=servicehook.url,
        data=json.dumps(payload),
        headers=headers,
        timeout=5,
        verify_ssl=(verify_ssl or False),
    )
开发者ID:Kayle009,项目名称:sentry,代码行数:18,代码来源:servicehooks.py


示例17: make_api_request

    def make_api_request(self, user, url, json_data=None):
        auth = self.get_auth_for_user(user=user)
        if auth is None:
            raise forms.ValidationError(_('You have not yet associated GitHub with your account.'))

        req_headers = {
            'Authorization': 'token %s' % auth.tokens['access_token'],
        }
        return safe_urlopen(url, json=json_data, headers=req_headers, allow_redirects=True)
开发者ID:getsentry,项目名称:sentry-github,代码行数:9,代码来源:plugin.py


示例18: _send_webhook

 def _send_webhook(self):
     safe_urlread(
         safe_urlopen(
             url=self.sentry_app.webhook_url,
             data=self.request.body,
             headers=self.request.headers,
             timeout=5,
         )
     )
开发者ID:Kayle009,项目名称:sentry,代码行数:9,代码来源:installation_notifier.py


示例19: test_ip_blacklist

 def test_ip_blacklist(self):
     http.DISALLOWED_IPS = set([IPNetwork('127.0.0.1'), IPNetwork('::1'), IPNetwork('10.0.0.0/8')])
     with pytest.raises(SuspiciousOperation):
         http.safe_urlopen('http://127.0.0.1')
     with pytest.raises(SuspiciousOperation):
         http.safe_urlopen('http://10.0.0.10')
     with pytest.raises(SuspiciousOperation):
         # '2130706433' is dword for '127.0.0.1'
         http.safe_urlopen('http://2130706433')
     with pytest.raises(SuspiciousOperation):
         # ipv6
         http.safe_urlopen('http://[::1]')
开发者ID:UNIVERSAL-IT-SYSTEMS,项目名称:sentry,代码行数:12,代码来源:test_http.py


示例20: _make_request

    def _make_request(self, endpoint, method, **kwargs):
        url = self.api_url + endpoint

        request_kwargs = {'method': method, 'headers': self.request_headers}

        body = kwargs.get('body')
        if body:
            request_kwargs['json'] = body

        return safe_urlopen(url, **request_kwargs)
开发者ID:getsentry,项目名称:sentry-plugins,代码行数:10,代码来源:client.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python http.safe_urlread函数代码示例发布时间:2022-05-27
下一篇:
Python http.build_session函数代码示例发布时间: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