Skip to content

Commit

Permalink
Merge pull request #149 from dotysan/lint
Browse files Browse the repository at this point in the history
chore 🧹: PEP8 linting
  • Loading branch information
subzero10 authored Jun 9, 2023
2 parents fe54076 + a452443 commit 6d3fa01
Show file tree
Hide file tree
Showing 37 changed files with 168 additions and 91 deletions.
2 changes: 1 addition & 1 deletion examples/django_app/app/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@
urlpatterns = [
re_path(r'^greet$', views.greet, name='greet'),
re_path(r'^div$', views.buggy_div, name='div'),
]
]
2 changes: 1 addition & 1 deletion examples/django_app/app/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,4 @@ def buggy_div(request):
"""
a = float(request.GET.get('a', '0'))
b = float(request.GET.get('b', '0'))
return JsonResponse({'result': a / b})
return JsonResponse({'result': a / b})
7 changes: 7 additions & 0 deletions examples/fastapi/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,30 +7,37 @@
app = FastAPI(title="Honeybadger - FastAPI with Middleware.")
app.add_middleware(contrib.ASGIHoneybadger, params_filters=["client"])


@app.get("/raise_some_error", tags=["Notify"])
def raise_some_error(a: str = "foo"):
"""Raises an error."""
raise Exception(f"SomeError Occurred (a = {a})")


class DivideRequest(pydantic.BaseModel):
a: int
b: int = 0


@app.post("/divide", response_model=float, tags=["Notify"])
def divide(req: DivideRequest):
"""Divides `a` by `b`."""
return req.a / req.b


@app.post("/raise_status_code", tags=["Don't Notify"])
def raise_status_code(status_code: int = 404, detail: str = "Forced 404."):
"""This exception is raised on purpose, so will not be notified."""
raise HTTPException(status_code=404, detail=detail)


some_router = APIRouter()


@some_router.get("/some_router/endpoint", tags=["Notify"])
def some_router_endpoint():
"""Try raising an error from a router."""
raise Exception("Exception Raised by some router endpoint.")


app.include_router(some_router)
7 changes: 7 additions & 0 deletions examples/fastapi/custom_route.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,30 +7,37 @@
app = FastAPI(title="Honeybadger - FastAPI with Custom Route.")
app.router.route_class = contrib.HoneybadgerRoute


@app.get("/raise_some_error", tags=["Notify"])
def raise_some_error(a: str = "foo"):
"""Raises an error."""
raise Exception(f"SomeError Occurred (a = {a})")


class DivideRequest(pydantic.BaseModel):
a: int
b: int = 0


@app.post("/divide", response_model=float, tags=["Notify"])
def divide(req: DivideRequest):
"""Divides `a` by `b`."""
return req.a / req.b


@app.post("/raise_status_code", tags=["Don't Notify"])
def raise_status_code(status_code: int = 404, detail: str = "Forced 404."):
"""This exception is raised on purpose, so will not be notified."""
raise HTTPException(status_code=404, detail=detail)


some_router = APIRouter(route_class=contrib.HoneybadgerRoute)


@some_router.get("/some_router/endpoint", tags=["Notify"])
def some_router_endpoint():
"""Try raising an error from a router."""
raise Exception("Exception Raised by some router endpoint.")


app.include_router(some_router)
7 changes: 5 additions & 2 deletions examples/try.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,19 @@
import logging
logging.getLogger('honeybadger').addHandler(logging.StreamHandler())


def method_two():
mydict = dict(a=1)
try:
print(mydict['b'])
print(mydict['b'])
except KeyError as exc:
honeybadger.notify(exc, context={'foo': 'bar'})
honeybadger.notify(exc, context={'foo': 'bar'})


def method_one():
method_two()


if __name__ == '__main__':
honeybadger.set_context(user_email="[email protected]")
method_one()
3 changes: 3 additions & 0 deletions examples/unhandled.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,16 @@
import logging
logging.getLogger('honeybadger').addHandler(logging.StreamHandler())


def method_two():
mydict = dict(a=1)
print(mydict['b'])


def method_one():
method_two()


if __name__ == '__main__':
honeybadger.set_context(user_email="[email protected]")
method_one()
6 changes: 3 additions & 3 deletions honeybadger/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from six.moves import zip
from six import iteritems


class Configuration(object):
DEVELOPMENT_ENVIRONMENTS = ['development', 'dev', 'test']

Expand Down Expand Up @@ -30,7 +31,7 @@ def __init__(self, *args, **kwargs):
self.force_sync = self.is_aws_lambda_environment
self.excluded_exceptions = []
self.report_local_variables = False

self.set_12factor_config()
self.set_config_from_dict(kwargs)

Expand All @@ -49,7 +50,6 @@ def set_12factor_config(self):
except:
pass


setattr(self, option, val)

def set_config_from_dict(self, config):
Expand All @@ -74,4 +74,4 @@ def is_aws_lambda_environment(self):
:rtype: bool
"""
return os.environ.get("AWS_LAMBDA_FUNCTION_NAME") is not None
return os.environ.get("AWS_LAMBDA_FUNCTION_NAME") is not None
7 changes: 3 additions & 4 deletions honeybadger/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@

logger = logging.getLogger(__name__)


def send_notice(config, payload):
notice_id = payload.get("error", {}).get("token", None)
request_object = request.Request(url="{}/v1/notices/".format(config.endpoint),
data=b(json.dumps(payload, cls=StringReprJSONEncoder)))
data=b(json.dumps(payload, cls=StringReprJSONEncoder)))

if not config.api_key:
logger.error("Honeybadger API key missing from configuration: cannot report errors.")
Expand All @@ -29,13 +30,11 @@ def send_request():
if status != 201:
logger.error("Received error response [{}] from Honeybadger API.".format(status))


if config.force_sync:
send_request()

else:
t = threading.Thread(target=send_request)
t.start()


return notice_id
13 changes: 9 additions & 4 deletions honeybadger/contrib/asgi.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def _looks_like_asgi3(app) -> bool:
return asyncio.iscoroutinefunction(app)
else:
call = getattr(app, "__call__", None)
return asyncio.iscoroutinefunction(call)
return asyncio.iscoroutinefunction(call)
return False


Expand All @@ -28,19 +28,21 @@ def _get_headers(scope: dict) -> dict:
headers[key] = value
return headers


def _get_query(scope: dict) -> str:
qs = scope.get("query_string")
if not qs:
return None
return urllib.parse.unquote(qs.decode("latin-1"))


def _get_url(scope: dict, default_scheme: str, host: str = None) -> str:
scheme = scope.get("scheme", default_scheme)
server = scope.get("server")
path = scope.get("root_path", "") + scope.get("path", "")
if host:
return "%s://%s%s" % (scheme, host, path)

if server is not None:
host, port = server
default_port = {"http": 80, "https": 443, "ws": 80, "wss": 443}[scheme]
Expand All @@ -49,6 +51,7 @@ def _get_url(scope: dict, default_scheme: str, host: str = None) -> str:
return "%s://%s%s" % (scheme, host, path)
return path


def _get_body(scope: dict) -> dict:
body = scope.get("body")
if body is None:
Expand All @@ -59,6 +62,7 @@ def _get_body(scope: dict) -> dict:
except:
return urllib.parse.unquote(body.decode("latin-1"))


def _as_context(scope: dict) -> dict:
ctx = {}
if scope.get("type") in ("http", "websocket"):
Expand All @@ -77,6 +81,7 @@ def _as_context(scope: dict) -> dict:
# TODO: should we look at "endpoint"?
return utils.filter_dict(ctx, honeybadger.config.params_filters)


class ASGIHoneybadger(plugins.Plugin):
__slots__ = ("__call__", "app")

Expand All @@ -102,7 +107,7 @@ async def inner(receive, send):

async def _run_asgi3(self, scope, receive, send):
return await self._run_app(scope, lambda: self.app(scope, receive, send))

async def _run_app(self, scope, callback):
# TODO: Should we check recursive middleware stacks?
# See: https://github.com/getsentry/sentry-python/blob/master/sentry_sdk/integrations/asgi.py#L112
Expand All @@ -116,6 +121,6 @@ async def _run_app(self, scope, callback):

def supports(self, config, context):
return context.get("asgi") is not None

def generate_payload(self, default_payload, config, context):
return utils.filter_dict(default_payload, honeybadger.config.params_filters)
33 changes: 17 additions & 16 deletions honeybadger/contrib/aws_lambda.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,26 +15,30 @@
_thread_locals = local()
REQUEST_LOCAL_KEY = '__awslambda_current_request'


def current_event():
"""
Return current execution event for this thread.
"""
return getattr(_thread_locals, REQUEST_LOCAL_KEY, None)


def set_event(aws_event):
"""
Set current execution event for this thread.
"""

setattr(_thread_locals, REQUEST_LOCAL_KEY, aws_event)


def clear_event():
"""
Clears execution event for this thread.
"""
if hasattr(_thread_locals, REQUEST_LOCAL_KEY):
setattr(_thread_locals, REQUEST_LOCAL_KEY, None)


def reraise(tp, value, tb=None):
"""
Re-raises a caught error
Expand All @@ -43,7 +47,8 @@ def reraise(tp, value, tb=None):
if value.__traceback__ is not tb:
raise value.with_traceback(tb)
raise value



def get_lambda_bootstrap():
"""
Get AWS Lambda bootstrap module
Expand All @@ -58,6 +63,7 @@ def get_lambda_bootstrap():
else:
return None


def _wrap_lambda_handler(handler):

def wrapped_handler(aws_event, aws_context, *args, **kwargs):
Expand All @@ -72,7 +78,7 @@ def wrapped_handler(aws_event, aws_context, *args, **kwargs):
clear_event()
honeybadger.reset_context()

#Rerase exception to proceed with normal aws error handling
# Rerase exception to proceed with normal aws error handling
reraise(*exc_info)

return wrapped_handler
Expand All @@ -86,7 +92,7 @@ def __init__(self):
if not lambda_bootstrap:
logger.warning('Lambda function not wrapped by honeybadger: Unable to locate bootstrap module.')
self.initialize_request_handler(lambda_bootstrap)

def supports(self, config, context):
return config.is_aws_lambda_environment

Expand Down Expand Up @@ -124,31 +130,31 @@ def generate_payload(self, default_payload, config, context):
default_payload["request"]["context"]["lambda_trace_id"] = trace_id

return default_payload

def initialize_request_handler(self, lambda_bootstrap):
"""
Here we fetch the http & event handler from the lambda bootstrap module
and override it with a wrapped version
"""
if hasattr(lambda_bootstrap, "handle_http_request"): #pre python3.7
if hasattr(lambda_bootstrap, "handle_http_request"): # pre python3.7
def event_handler(request_handler, *args, **kwargs):
request_handler = _wrap_lambda_handler(request_handler)
return original_event_handler(request_handler, *args, **kwargs)

def http_handler(request_handler, *args, **kwargs):
request_handler = _wrap_lambda_handler(request_handler)
return original_http_handler(request_handler, *args, **kwargs)

try:
#Get and replace the original handler for events with a wrapped one
# Get and replace the original handler for events with a wrapped one
original_event_handler = lambda_bootstrap.handle_event_request
original_http_handler = lambda_bootstrap.handle_http_request
lambda_bootstrap.handle_event_request = event_handler
lambda_bootstrap.handle_http_request = http_handler

except AttributeError as e: #Fail safely if we can't monkeypatch lambda handler
logger.warning('Lambda function not wrapped by honeybadger: %s' %e)
except AttributeError as e: # Fail safely if we can't monkeypatch lambda handler
logger.warning('Lambda function not wrapped by honeybadger: %s' % e)

else:
def event_handler(lambda_runtime_client, request_handler, *args, **kwargs):
request_handler = _wrap_lambda_handler(request_handler)
Expand All @@ -163,9 +169,4 @@ def event_handler(lambda_runtime_client, request_handler, *args, **kwargs):
# either of these will raise an Attribute error as "handle_event_request" or "handle_event_request"
# may not be found.
except AttributeError as e:
logger.warning('Lambda function not wrapped by honeybadger: %s' %e)





logger.warning('Lambda function not wrapped by honeybadger: %s' % e)
1 change: 1 addition & 0 deletions honeybadger/contrib/celery.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from honeybadger import honeybadger
from honeybadger.plugins import Plugin, default_plugin_manager


class CeleryPlugin(Plugin):
def __init__(self):
super().__init__("Celery")
Expand Down
Loading

0 comments on commit 6d3fa01

Please sign in to comment.