本文整理汇总了Python中sentry.utils.json.dumps函数的典型用法代码示例。如果您正苦于以下问题:Python dumps函数的具体用法?Python dumps怎么用?Python dumps使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了dumps函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: open_resolve_dialog
def open_resolve_dialog(self, data, group, integration):
# XXX(epurkhiser): In order to update the original message we have to
# keep track of the response_url in the callback_id. Definitely hacky,
# but seems like there's no other solutions [1]:
#
# [1]: https://stackoverflow.com/questions/46629852/update-a-bot-message-after-responding-to-a-slack-dialog#comment80795670_46629852
callback_id = json.dumps({
'issue': group.id,
'orig_response_url': data['response_url'],
'is_message': self.is_message(data),
})
dialog = {
'callback_id': callback_id,
'title': u'Resolve Issue',
'submit_label': 'Resolve',
'elements': [RESOLVE_SELECTOR],
}
payload = {
'dialog': json.dumps(dialog),
'trigger_id': data['trigger_id'],
'token': integration.metadata['access_token'],
}
session = http.build_session()
req = session.post('https://slack.com/api/dialog.open', data=payload)
resp = req.json()
if not resp.get('ok'):
logger.error('slack.action.response-error', extra={'response': resp})
开发者ID:Kayle009,项目名称:sentry,代码行数:30,代码来源:action_endpoint.py
示例2: _publish_to_kafka
def _publish_to_kafka(self, request):
"""
Sends raw event data to Kafka for later offline processing.
"""
try:
# This may fail when we e.g. send a multipart form. We ignore those errors for now.
data = request.body
if not data or len(data) > options.get('kafka-publisher.max-event-size'):
return
# Sampling
if random.random() >= options.get('kafka-publisher.raw-event-sample-rate'):
return
# We want to send only serializable items from request.META
meta = {}
for key, value in request.META.items():
try:
json.dumps([key, value])
meta[key] = value
except (TypeError, ValueError):
pass
meta['SENTRY_API_VIEW_NAME'] = self.__class__.__name__
kafka_publisher.publish(
channel=getattr(settings, 'KAFKA_RAW_EVENTS_PUBLISHER_TOPIC', 'raw-store-events'),
value=json.dumps([meta, base64.b64encode(data)])
)
except Exception as e:
logger.debug("Cannot publish event to Kafka: {}".format(e.message))
开发者ID:Kayle009,项目名称:sentry,代码行数:32,代码来源:api.py
示例3: process_service_hook
def process_service_hook(servicehook_id, event, **kwargs):
try:
servicehook = ServiceHook.objects.get(id=servicehook_id)
except ServiceHook.DoesNotExist:
return
if servicehook.version == 0:
payload = get_payload_v0(event)
else:
raise NotImplementedError
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=False,
)
开发者ID:yaoqi,项目名称:sentry,代码行数:28,代码来源:servicehooks.py
示例4: get
def get(self, request, organization, team, project, rule_id=None):
if rule_id:
try:
rule = Rule.objects.get(project=project, id=rule_id)
except Rule.DoesNotExist:
path = reverse('sentry-project-rules', args=[organization.slug, project.slug])
return self.redirect(path)
else:
rule = Rule(project=project)
action_list = []
condition_list = []
# TODO: conditions need to be based on actions
for rule_type, rule_cls in rules:
node = rule_cls(project)
context = {
'id': node.id,
'label': node.label,
'html': node.render_form(),
}
if rule_type.startswith('condition/'):
condition_list.append(context)
elif rule_type.startswith('action/'):
action_list.append(context)
context = {
'rule': rule,
'page': 'rules',
'action_list': json.dumps(action_list),
'condition_list': json.dumps(condition_list),
}
return self.respond('sentry/projects/rules/new.html', context)
开发者ID:280185386,项目名称:sentry,代码行数:35,代码来源:project_rule_edit.py
示例5: dispatch
def dispatch(self, request):
try:
event_id = request.GET['eventId']
except KeyError:
return self._json_response(request, status=400)
key = self._get_project_key(request)
if not key:
return self._json_response(request, status=404)
origin = self._get_origin(request)
if not origin:
return self._json_response(request, status=403)
if not is_valid_origin(origin, key.project):
return HttpResponse(status=403)
if request.method == 'OPTIONS':
return self._json_response(request)
# TODO(dcramer): since we cant use a csrf cookie we should at the very
# least sign the request / add some kind of nonce
initial = {
'name': request.GET.get('name'),
'email': request.GET.get('email'),
}
form = UserReportForm(request.POST if request.method == 'POST' else None,
initial=initial)
if form.is_valid():
report = form.save(commit=False)
report.project = key.project
report.event_id = event_id
try:
report.group = Group.objects.get(
eventmapping__event_id=report.event_id,
eventmapping__project=key.project,
)
except Group.DoesNotExist:
# XXX(dcramer): the system should fill this in later
pass
report.save()
return HttpResponse(status=200)
elif request.method == 'POST':
return self._json_response(request, {
"errors": dict(form.errors),
}, status=400)
template = render_to_string('sentry/error-page-embed.html', {
'form': form,
})
context = {
'endpoint': mark_safe(json.dumps(request.get_full_path())),
'template': mark_safe(json.dumps(template)),
}
return render_to_response('sentry/error-page-embed.js', context, request,
content_type='text/javascript')
开发者ID:AyrtonRicardo,项目名称:sentry,代码行数:59,代码来源:error_page_embed.py
示例6: test_escape
def test_escape(self):
res = "<script>alert('&');</script>"
assert json.dumps(res) == '"<script>alert(\'&\');</script>"'
assert json.dumps(
res, escape=True
) == '"\\u003cscript\\u003ealert(\\u0027\u0026\\u0027);\\u003c/script\\u003e"'
assert json.dumps_htmlsafe(
res
) == '"\\u003cscript\\u003ealert(\\u0027\u0026\\u0027);\\u003c/script\\u003e"'
开发者ID:yaoqi,项目名称:sentry,代码行数:9,代码来源:tests.py
示例7: test_valid_member_selected
def test_valid_member_selected(self):
rule = self.get_rule(data={
'workspace': self.integration.id,
'channel': '@morty',
'tags': '',
})
channels = {
'ok': 'true',
'channels': [
{'name': 'my-channel', 'id': 'chan-id'},
{'name': 'other-chann', 'id': 'chan-id'},
],
}
responses.add(
method=responses.GET,
url='https://slack.com/api/channels.list',
status=200,
content_type='application/json',
body=json.dumps(channels),
)
groups = {
'ok': 'true',
'groups': [
{'name': 'my-private-channel', 'id': 'chan-id'},
],
}
responses.add(
method=responses.GET,
url='https://slack.com/api/groups.list',
status=200,
content_type='application/json',
body=json.dumps(groups),
)
members = {
'ok': 'true',
'members': [
{'name': 'morty', 'id': 'morty-id'},
{'name': 'other-user', 'id': 'user-id'},
],
}
responses.add(
method=responses.GET,
url='https://slack.com/api/users.list',
status=200,
content_type='application/json',
body=json.dumps(members),
)
form = rule.get_form_instance()
assert form.is_valid()
开发者ID:binlee1990,项目名称:sentry,代码行数:56,代码来源:test_notify_action.py
示例8: to_python
def to_python(cls, data):
if not data.get('message'):
raise InterfaceValidationError("No 'message' present")
# TODO(dcramer): some day we should stop people from sending arbitrary
# crap to the server
if not isinstance(data['message'], six.string_types):
data['message'] = json.dumps(data['message'])
kwargs = {
'message': trim(data['message'], settings.SENTRY_MAX_MESSAGE_LENGTH),
'formatted': data.get('formatted'),
}
if data.get('params'):
kwargs['params'] = trim(data['params'], 1024)
else:
kwargs['params'] = ()
if kwargs['formatted']:
if not isinstance(kwargs['formatted'], six.string_types):
data['formatted'] = json.dumps(data['formatted'])
# support python-esque formatting (e.g. %s)
elif '%' in kwargs['message'] and kwargs['params']:
if isinstance(kwargs['params'], list):
kwargs['params'] = tuple(kwargs['params'])
try:
kwargs['formatted'] = trim(
kwargs['message'] % kwargs['params'],
settings.SENTRY_MAX_MESSAGE_LENGTH,
)
except Exception:
pass
# support very basic placeholder formatters (non-typed)
elif '{}' in kwargs['message'] and kwargs['params']:
try:
kwargs['formatted'] = trim(
kwargs['message'].format(kwargs['params']),
settings.SENTRY_MAX_MESSAGE_LENGTH,
)
except Exception:
pass
# don't wastefully store formatted message twice
if kwargs['formatted'] == kwargs['message']:
kwargs['formatted'] = None
return cls(**kwargs)
开发者ID:ForkRepo,项目名称:sentry,代码行数:49,代码来源:message.py
示例9: test_no_actor
def test_no_actor(self):
result = AppPlatformEvent(
resource='event_alert',
action='triggered',
install=self.install,
data={},
)
assert result.body == {
'action': 'triggered',
'installation': {
'uuid': self.install.uuid,
},
'data': {},
'actor': {
'type': 'application',
'id': 'sentry',
'name': 'Sentry',
}
}
body = json.dumps(result.body)
signature = self.sentry_app.build_signature(body)
assert result.headers['Content-Type'] == 'application/json'
assert result.headers['Sentry-Hook-Resource'] == 'event_alert'
assert result.headers['Sentry-Hook-Signature'] == signature
开发者ID:Kayle009,项目名称:sentry,代码行数:25,代码来源:test_app_platform_event.py
示例10: chart
def chart(request, team=None, project=None):
gid = request.REQUEST.get('gid')
days = int(request.REQUEST.get('days', '90'))
if gid:
try:
group = Group.objects.get(pk=gid)
except Group.DoesNotExist:
return HttpResponseForbidden()
data = Group.objects.get_chart_data(group, max_days=days)
elif project:
data = Project.objects.get_chart_data(project, max_days=days)
elif team:
cache_key = 'api.chart:team=%s,days=%s' % (team.id, days)
data = cache.get(cache_key)
if data is None:
project_list = list(Project.objects.filter(team=team))
data = Project.objects.get_chart_data_for_group(project_list, max_days=days)
cache.set(cache_key, data, 300)
else:
cache_key = 'api.chart:user=%s,days=%s' % (request.user.id, days)
data = cache.get(cache_key)
if data is None:
project_list = Project.objects.get_for_user(request.user)
data = Project.objects.get_chart_data_for_group(project_list, max_days=days)
cache.set(cache_key, data, 300)
response = HttpResponse(json.dumps(data))
response['Content-Type'] = 'application/json'
return response
开发者ID:BlaShadow,项目名称:sentry,代码行数:32,代码来源:api.py
示例11: get_stats
def get_stats(request, team=None, project=None):
minutes = int(request.REQUEST.get('minutes', 15))
if not team and project:
project_list = [project]
else:
project_list = Project.objects.get_for_user(request.user, team=team)
cutoff = datetime.timedelta(minutes=minutes)
cutoff_dt = timezone.now() - cutoff
num_events = ProjectCountByMinute.objects.filter(
project__in=project_list,
date__gte=cutoff_dt,
).aggregate(t=Sum('times_seen'))['t'] or 0
# XXX: This is too slow if large amounts of groups are resolved
num_resolved = Group.objects.filter(
project__in=project_list,
status=STATUS_RESOLVED,
resolved_at__gte=cutoff_dt,
).aggregate(t=Sum('times_seen'))['t'] or 0
data = {
'events': num_events,
'resolved': num_resolved,
}
response = HttpResponse(json.dumps(data))
response['Content-Type'] = 'application/json'
return response
开发者ID:BlaShadow,项目名称:sentry,代码行数:32,代码来源:api.py
示例12: get_group_trends
def get_group_trends(request, project=None):
minutes = int(request.REQUEST.get("minutes", 15))
limit = min(100, int(request.REQUEST.get("limit", 10)))
if project:
project_dict = {project.pk: project}
else:
project_dict = get_project_list(request.user)
base_qs = Group.objects.filter(project__in=project_dict.keys(), status=0).order_by("-score")
if has_trending():
group_list = list(Group.objects.get_accelerated(base_qs, minutes=(minutes))[:limit])
else:
cutoff = datetime.timedelta(minutes=minutes)
cutoff_dt = timezone.now() - cutoff
group_list = list(base_qs.filter(last_seen__gte=cutoff_dt)[:limit])
for group in group_list:
group._project_cache = project_dict.get(group.project_id)
data = transform_groups(request, group_list, template="sentry/partial/_group_small.html")
response = HttpResponse(json.dumps(data))
response["Content-Type"] = "application/json"
return response
开发者ID:nkabir,项目名称:sentry,代码行数:28,代码来源:api.py
示例13: get_resolved_groups
def get_resolved_groups(request, team=None, project=None):
minutes = int(request.REQUEST.get('minutes', 15))
limit = min(100, int(request.REQUEST.get('limit', 10)))
if team:
project_list = list(Project.objects.filter(team=team))
elif project:
project_list = [project]
else:
project_list = get_project_list(request.user).values()
cutoff = datetime.timedelta(minutes=minutes)
cutoff_dt = timezone.now() - cutoff
group_list = Group.objects.filter(
project__in=project_list,
status=STATUS_RESOLVED,
resolved_at__gte=cutoff_dt,
).select_related('project').order_by('-score')[:limit]
data = to_json(group_list, request)
response = HttpResponse(json.dumps(data))
response['Content-Type'] = 'application/json'
return response
开发者ID:TracyWebTech,项目名称:sentry,代码行数:26,代码来源:api.py
示例14: bookmark
def bookmark(request, project):
gid = request.REQUEST.get('gid')
if not gid:
return HttpResponseForbidden()
if not request.user.is_authenticated():
return HttpResponseForbidden()
try:
group = Group.objects.get(pk=gid)
except Group.DoesNotExist:
return HttpResponseForbidden()
if group.project and group.project.pk not in get_project_list(request.user):
return HttpResponseForbidden()
gb, created = GroupBookmark.objects.get_or_create(
project=group.project,
user=request.user,
group=group,
)
if not created:
gb.delete()
response = HttpResponse(json.dumps({'bookmarked': created}))
response['Content-Type'] = 'application/json'
return response
开发者ID:twoolie,项目名称:sentry,代码行数:27,代码来源:api.py
示例15: test_valid_params
def test_valid_params(self):
resp = self.client.post(self.path, data=json.dumps({
'version': 'a',
}), content_type='application/json')
assert resp.status_code == 201, resp.content
data = json.loads(resp.content)
assert data['version'] == 'a'
开发者ID:ForkRepo,项目名称:sentry,代码行数:7,代码来源:test_release_webhook.py
示例16: serialize
def serialize(context, obj):
if 'request' in context:
user = context['request'].user
else:
user = None
return mark_safe(json.dumps(serialize_func(obj, user)))
开发者ID:280185386,项目名称:sentry,代码行数:7,代码来源:sentry_api.py
示例17: test_post_success
def test_post_success(self, process):
process.return_value = 'ok'
resp = self.client.post(
self.path,
content_type='application/expect-ct-report+json',
data=json.dumps({
"expect-ct-report": {
"date-time": "2014-04-06T13:00:50Z",
"hostname": "www.example.com",
"port": 443,
"effective-expiration-date": "2014-05-01T12:40:50Z",
"served-certificate-chain": ["-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----"],
"validated-certificate-chain": ["-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----"],
"scts": [
{
"version": 1,
"status": "invalid",
"source": "embedded",
"serialized_sct": "ABCD=="
},
],
}
}),
HTTP_USER_AGENT='awesome',
)
assert resp.status_code == 201, resp.content
开发者ID:hosmelq,项目名称:sentry,代码行数:26,代码来源:tests.py
示例18: _handle_builtin
def _handle_builtin(self, request, project):
endpoint = '/projects/{}/{}/releases/'.format(
project.organization.slug,
project.slug,
)
try:
# Ideally the API client would support some kind of god-mode here
# as we've already confirmed credentials and simply want to execute
# the view code. Instead we hack around it with an ApiKey instance
god = ApiKey(
organization=project.organization,
scopes=getattr(ApiKey.scopes, 'project:write'),
)
resp = client.post(
endpoint,
data=json.loads(request.body),
auth=god,
)
except client.ApiError as exc:
return HttpResponse(
status=exc.status_code,
content=exc.body,
content_type='application/json',
)
return HttpResponse(
status=resp.status_code,
content=json.dumps(resp.data),
content_type='application/json',
)
开发者ID:AyrtonRicardo,项目名称:sentry,代码行数:30,代码来源:release_webhook.py
示例19: get_react_config
def get_react_config(context):
if 'request' in context:
user = context['request'].user
else:
user = None
if user:
user = extract_lazy_object(user)
enabled_features = []
if features.has('organizations:create', actor=user):
enabled_features.append('organizations:create')
if features.has('auth:register', actor=user):
enabled_features.append('auth:register')
context = {
'singleOrganization': settings.SENTRY_SINGLE_ORGANIZATION,
'urlPrefix': settings.SENTRY_URL_PREFIX,
'version': _get_version_info(),
'features': enabled_features,
'mediaUrl': reverse('sentry-media', args=['sentry', '']),
}
if user and user.is_authenticated():
context.update({
'isAuthenticated': True,
'user': serialize(user, user),
})
else:
context.update({
'isAuthenticated': False,
'user': None,
})
return mark_safe(json.dumps(context))
开发者ID:carriercomm,项目名称:sentry-1,代码行数:33,代码来源:sentry_react.py
示例20: to_python
def to_python(cls, data, has_system_frames=None):
if not (data.get('type') or data.get('value')):
raise InterfaceValidationError("No 'type' or 'value' present")
if data.get('stacktrace') and data['stacktrace'].get('frames'):
stacktrace = Stacktrace.to_python(
data['stacktrace'],
has_system_frames=has_system_frames,
)
else:
stacktrace = None
type = data.get('type')
value = data.get('value')
if not type and ':' in value.split(' ', 1)[0]:
type, value = value.split(':', 1)
# in case of TypeError: foo (no space)
value = value.strip()
if value is not None and not isinstance(value, basestring):
value = json.dumps(value)
value = trim(value, 4096)
kwargs = {
'type': trim(type, 128),
'value': value,
'module': trim(data.get('module'), 128),
'stacktrace': stacktrace,
}
return cls(**kwargs)
开发者ID:zhoupan,项目名称:sentry,代码行数:31,代码来源:exception.py
注:本文中的sentry.utils.json.dumps函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论