8000 Sourcery refactored master branch by sourcery-ai[bot] · Pull Request #1 · Edrolo/sentry-python · GitHub
[go: up one dir, main page]

Skip to content

Sourcery refactored master branch #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
'Refactored by Sourcery'
  • Loading branch information
Sourcery AI committed Dec 1, 2021
commit 33b2e5787411766e537f0ad7100e100b1fa34316
5 changes: 2 additions & 3 deletions examples/tracing/tracing.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,8 @@ def wait(redis_key):
result = redis_conn.get(redis_key)
if result is None:
return "NONE"
else:
redis_conn.delete(redis_key)
return "RESULT: {}".format(result)
redis_conn.delete(redis_key)
return "RESULT: {}".format(result)
Comment on lines -63 to +64
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function wait refactored with the following changes:



@app.cli.command("worker")
Expand Down
5 changes: 1 addition & 4 deletions sentry_sdk/attachments.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,7 @@ def to_envelope_item(self):
"""Returns an envelope item for this attachment."""
payload = None # type: Union[None, PayloadRef, bytes]
if self.bytes is not None:
if callable(self.bytes):
payload = self.bytes()
else:
payload = self.bytes
payload = self.bytes() if callable(self.bytes) else self.bytes
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Attachment.to_envelope_item refactored with the following changes:

else:
payload = PayloadRef(path=self.path)
return Item(
Expand Down
23 changes: 8 additions & 15 deletions sentry_sdk/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,17 +214,13 @@ def _is_ignored_error(self, event, hint):
type_name = get_type_name(exc_info[0])
full_name = "%s.%s" % (exc_info[0].__module__, type_name)

for errcls in self.options["ignore_errors"]:
# String types are matched against the type name in the
# exception only
if isinstance(errcls, string_types):
if errcls == full_name or errcls == type_name:
return True
else:
if issubclass(exc_info[0], errcls):
return True

return False
return any(
isinstance(errcls, string_types)
and errcls in [full_name, type_name]
or not isinstance(errcls, string_types)
and issubclass(exc_info[0], errcls)
for errcls in self.options["ignore_errors"]
)
Comment on lines -217 to +223
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _Client._is_ignored_error refactored with the following changes:

This removes the following comments ( why? ):

# String types are matched against the type name in the
# exception only


def _should_capture(
self,
Expand All @@ -249,10 +245,7 @@ def _should_capture(
self.transport.record_lost_event("sample_rate", data_category="error")
return False

if self._is_ignored_error(event, hint):
return False

return True
return not self._is_ignored_error(event, hint)
Comment on lines -252 to +248
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _Client._should_capture refactored with the following changes:


def _update_session_from_event(
self,
Expand Down
10 changes: 2 additions & 8 deletions sentry_sdk/envelope.py
F438
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,7 @@ def __init__(
if headers is not None:
headers = dict(headers)
self.headers = headers or {}
if items is None:
items = []
else:
items = list(items)
items = [] if items is None else list(items)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Envelope.__init__ refactored with the following changes:

self.items = items

@property
Expand Down Expand Up @@ -196,10 +193,7 @@ def __init__(
content_type=None, # type: Optional[str]
filename=None, # type: Optional[str]
):
if headers is not None:
headers = dict(headers)
elif headers is None:
headers = {}
headers = dict(headers) if headers is not None else {}
Comment on lines -199 to +196
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Item.__init__ refactored with the following changes:

self.headers = headers
if isinstance(payload, bytes):
payload = PayloadRef(bytes=payload)
Expand Down
26 changes: 10 additions & 16 deletions sentry_sdk/hub.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,7 @@ def _init(*args, **kwargs):
"""
client = Client(*args, **kwargs) # type: ignore
Hub.current.bind_client(client)
rv = _InitGuard(client)
return rv
return _InitGuard(client)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _init refactored with the following changes:



from sentry_sdk._types import MYPY
Expand Down Expand Up @@ -362,11 +361,7 @@ def capture_exception(
client = self.client
if client is None:
return None
if error is not None:
exc_info = exc_info_from_error(error)
else:
exc_info = sys.exc_info()

exc_info = exc_info_from_error(error) if error is not None else sys.exc_info()
Comment on lines -365 to +364
Copy link
10000 Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Hub.capture_exception refactored with the following changes:

event, hint = event_from_exception(exc_info, client_options=client.options)
try:
return self.capture_event(event, hint=hint, scope=scope, **scope_args)
Expand Down Expand Up @@ -458,13 +453,13 @@ def start_span(
"Deprecated: use start_transaction to start transactions and "
"Transaction.start_child to start spans."
)
if isinstance(span, Transaction):
logger.warning(deprecation_msg)
return self.start_transaction(span)
if "transaction" in kwargs:
logger.warning(deprecation_msg)
name = kwargs.pop("transaction")
return self.start_transaction(name=name, **kwargs)
if isinstance(span, Transaction):
logger.warning(deprecation_msg)
return self.start_transaction(span)
if "transaction" in kwargs:
logger.warning(deprecation_msg)
name = kwargs.pop("transaction")
return self.start_transaction(name=name, **kwargs)
Comment on lines -461 to +462
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Hub.start_span refactored with the following changes:


if span is not None:
return span
Expand Down Expand Up @@ -700,8 +695,7 @@ def iter_trace_propagation_headers(self, span=None):
if not propagate_traces:
return

for header in span.iter_headers():
yield header
yield from span.iter_headers()
Comment on lines -703 to +698
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Hub.iter_trace_propagation_headers refactored with the following changes:

  • Replace yield inside for loop with yield from (yield-from)



GLOBAL_HUB = Hub()
Expand Down
23 changes: 12 additions & 11 deletions sentry_sdk/integrations/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,11 @@ def setup_integrations(
`with_defaults` is set to `True` then all default integrations are added
unless they were already provided before.
"""
integrations = dict(
(integration.identifier, integration) for integration in integrations or ()
)
integrations = {
integration.identifier: integration
for integration in integrations or ()
}

Comment on lines -95 to +99
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _generate_default_integrations_iterator.iter_default_integrations.setup_integrations refactored with the following changes:


logger.debug("Setting up integrations (with default = %s)", with_defaults)

Expand All @@ -119,15 +121,14 @@ def setup_integrations(
try:
type(integration).setup_once()
except NotImplementedError:
if getattr(integration, "install", None) is not None:
logger.warning(
"Integration %s: The install method is "
"deprecated. Use `setup_once`.",
identifier,
)
integration.install()
else:
if getattr(integration, "install", None) is None:
raise
logger.warning(
"Integration %s: The install method is "
"deprecated. Use `setup_once`.",
identifier,
)
integration.install()
except DidNotEnable as e:
if identifier not in used_as_default_integration:
raise
Expand Down
10 changes: 2 additions & 8 deletions sentry_sdk/integrations/asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,10 +88,7 @@ def __init__(self, app, unsafe_context_data=False):
)
self.app = app

if _looks_like_asgi3(app):
self.__call__ F438 = self._run_asgi3 # type: Callable[..., Any]
else:
self.__call__ = self._run_asgi2
self.__call__ = self._run_asgi3 if _looks_like_asgi3(app) else self._run_asgi2
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function SentryAsgiMiddleware.__init__ refactored with the following changes:

This removes the following comments ( why? ):

# type: Callable[..., Any]


def _run_asgi2(self, scope):
# type: (Any) -> Any
Expand Down Expand Up @@ -252,8 +249,5 @@ def _get_headers(self, scope):
for raw_key, raw_value in scope["headers"]:
key = raw_key.decode("latin-1")
value = raw_value.decode("latin-1")
if key in headers:
headers[key] = headers[key] + ", " + value
else:
headers[key] = value
headers[key] = headers[key] + ", " + value if key in headers else value
Comment on lines -255 to +252
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function SentryAsgiMiddleware._get_headers refactored with the following changes:

return headers
13 changes: 5 additions & 8 deletions sentry_sdk/integrations/aws_lambda.py
Original file line number Diff line number Diff line change
Expand Up @@ -360,11 +360,10 @@ def event_processor(sentry_event, hint, start_time=start_time):

if "body" in aws_event:
request["data"] = aws_event.get("body", "")
else:
if aws_event.get("body", None):
# Unfortunately couldn't find a way to get structured body from AWS
# event. Meaning every body is unstructured to us.
request["data"] = AnnotatedValue("", {"rem": [["!raw", "x", 0, 0]]})
elif aws_event.get("body", None):
# Unfortunately couldn't find a way to get structured body from AWS
# event. Meaning every body is unstructured to us.
request["data"] = AnnotatedValue("", {"rem": [["!raw", "x", 0, 0]]})
Comment on lines -363 to +366
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _make_request_event_processor.event_processor refactored with the following changes:


sentry_event["request"] = request

Expand Down Expand Up @@ -402,7 +401,7 @@ def _get_cloudwatch_logs_url(aws_context, start_time):
formatstring = "%Y-%m-%dT%H:%M:%SZ"
region = environ.get("AWS_REGION", "")

url = (
return (
Comment on lines -405 to +404
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _get_cloudwatch_logs_url refactored with the following changes:

"https://console.{domain}/cloudwatch/home?region={region}"
"#logEventViewer:group={log_group};stream={log_stream}"
";start={start_time};end={end_time}"
Expand All @@ -414,5 +413,3 @@ def _get_cloudwatch_logs_url(aws_context, start_time):
start_time=(start_time - timedelta(seconds=1)).strftime(formatstring),
end_time=(datetime.utcnow() + timedelta(seconds=2)).strftime(formatstring),
)

return url
39 changes: 19 additions & 20 deletions sentry_sdk/integrations/celery.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,27 +95,26 @@ def apply_async(*args, **kwargs):
# type: (*Any, **Any) -> Any
hub = Hub.current
integration = hub.get_integration(CeleryIntegration)
if integration is not None and integration.propagate_traces:
with hub.start_span(op="celery.submit", description=args[0].name) as span:
with capture_internal_exceptions():
headers = dict(hub.iter_trace_propagation_headers(span))

if headers:
# Note: kwargs can contain headers=None, so no setdefault!
# Unsure which backend though.
kwarg_headers = kwargs.get("headers") or {}
kwarg_headers.update(headers)

# https://github.com/celery/celery/issues/4875
#
# Need to setdefault the inner headers too since other
# tracing tools (dd-trace-py) also employ this exact
# workaround and we don't want to break them.
kwa 10000 rg_headers.setdefault("headers", {}).update(headers)
kwargs["headers"] = kwarg_headers
if integration is None or not integration.propagate_traces:
return f(*args, **kwargs)
with hub.start_span(op="celery.submit", description=args[0].name) as span:
with capture_internal_exceptions():
headers = dict(hub.iter_trace_propagation_headers(span))

if headers:
# Note: kwargs can contain headers=None, so no setdefault!
# Unsure which backend though.
kwarg_headers = kwargs.get("headers") or {}
kwarg_headers.update(headers)

# https://github.com/celery/celery/issues/4875
#
# Need to setdefault the inner headers too since other
# tracing tools (dd-trace-py) also employ this exact
# workaround and we don't want to break them.
kwarg_headers.setdefault("headers", {}).update(headers)
kwargs["headers"] = kwarg_headers

return f(*args, **kwargs)
else:
Comment on lines -98 to -118
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _wrap_apply_async.apply_async refactored with the following changes:

return f(*args, **kwargs)

return apply_async # type: ignore
Expand Down
1 change: 0 additions & 1 deletion sentry_sdk/integrations/django/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,6 @@ def sentry_patched_drf_initial(self, request, *args, **kwargs):
request._request._sentry_drf_request_backref = weakref.ref(
request
)
pass
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _patch_drf.sentry_patched_drf_initial refactored with the following changes:

return old_drf_initial(self, request, *args, **kwargs)

APIView.initial = sentry_patched_drf_initial
Expand Down
8 changes: 3 additions & 5 deletions sentry_sdk/integrations/django/templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,10 @@ def get_template_frame_from_exception(exc_value):


def _get_template_name_description(template_name):
# type: (str) -> str
if isinstance(template_name, (list, tuple)):
if template_name:
return "[{}, ...]".format(template_name[0])
else:
if not isinstance(template_name, (list, tuple)):
return template_name
if template_name:
return "[{}, ...]".format(template_name[0])
Comment on lines -46 to +49
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _get_template_name_description refactored with the following changes:

This removes the following comments ( why? ):

# type: (str) -> str



def patch_templates():
Expand Down
6 changes: 1 addition & 5 deletions sentry_sdk/integrations/falcon.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,11 +143,7 @@ def sentry_patched_handle_exception(self, *args):
# NOTE(jmagnusson): falcon 2.0 changed falcon.API._handle_exception
# method signature from `(ex, req, resp, params)` to
# `(req, resp, ex, params)`
if isinstance(args[0], Exception):
ex = args[0]
else:
ex = args[2]

ex = args[0] if isinstance(args[0], Exception) else args[2]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _patch_handle_exception.sentry_patched_handle_exception refactored with the following changes:

was_handled = original_handle_exception(self, *args)

hub = Hub.current
Expand Down
17 changes: 6 additions & 11 deletions sentry_sdk/integrations/gcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,7 @@ def sentry_func(functionhandler, gcp_event, *args, **kwargs):
# Starting the thread to raise timeout warning exception
timeout_thread.start()

headers = {}
if hasattr(gcp_event, "headers"):
headers = gcp_event.headers
headers = gcp_event.headers if hasattr(gcp_event, "headers") else {}
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _wrap_func.sentry_func refactored with the following changes:

transaction = Transaction.continue_from_headers(
headers, op="serverless.function", name=environ.get("FUNCTION_NAME", "")
)
Expand Down Expand Up @@ -183,11 +181,10 @@ def event_processor(event, hint):
if _should_send_default_pii():
if hasattr(gcp_event, "data"):
request["data"] = gcp_event.data
else:
if hasattr(gcp_event, 4E34 "data"):
# Unfortunately couldn't find a way to get structured body from GCP
# event. Meaning every body is unstructured to us.
request["data"] = AnnotatedValue("", {"rem": [["!raw", "x", 0, 0]]})
elif hasattr(gcp_event, "data"):
# Unfortunately couldn't find a way to get structured body from GCP
# event. Meaning every body is unstructured to us.
request["data"] = AnnotatedValue("", {"rem": [["!raw", "x", 0, 0]]})
Comment on lines -186 to +187
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _make_request_event_processor.event_processor refactored with the following changes:


event["request"] = request

Expand All @@ -208,7 +205,7 @@ def _get_google_cloud_logs_url(final_time):
hour_ago = final_time - timedelta(hours=1)
formatstring = "%Y-%m-%dT%H:%M:%SZ"

url = (
return (
Comment on lines -211 to +208
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _get_google_cloud_logs_url refactored with the following changes:

"https://console.cloud.google.com/logs/viewer?project={project}&resource=cloud_function"
"%2Ffunction_name%2F{function_name}%2Fregion%2F{region}&minLogLevel=0&expandAll=false"
"&timestamp={timestamp_end}&customFacets=&limitCustomFacetWidth=true"
Expand All @@ -221,5 +218,3 @@ def _get_google_cloud_logs_url(final_time):
timestamp_end=final_time.strftime(formatstring),
timestamp_start=hour_ago.strftime(formatstring),
)

return url
7 changes: 2 additions & 5 deletions sentry_sdk/integrations/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,7 @@ def sentry_patched_callhandlers(self, record):
def _can_record(record):
# type: (LogRecord) -> bool
"""Prevents ignored loggers from recording"""
for logger in _IGNORED_LOGGERS:
if fnmatch(record.name, logger):
return False
return True
return not any(fnmatch(record.name, logger) for logger in _IGNORED_LOGGERS)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _can_record refactored with the following changes:

  • Use any() instead of for loop (use-any)



def _breadcrumb_from_record(record):
Expand Down Expand Up @@ -199,7 +196,7 @@ def _emit(self, record):
client_options=client_options,
mechanism={"type": "logging", "handled": True},
)
elif record.exc_info and record.exc_info[0] is None:
elif record.exc_info:
Comment on lines -202 to +199
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function EventHandler._emit refactored with the following changes:

event = {}
hint = {}
with capture_internal_exceptions():
Expand Down
Loading
0