gotisink 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
gotisink/__init__.py ADDED
@@ -0,0 +1,49 @@
1
+ import os
2
+ from urllib.parse import urlparse
3
+
4
+ import sentry_sdk
5
+
6
+ from gotisink.django import gotify_handler
7
+
8
+
9
+ def init(
10
+ dsn: str | None = None,
11
+ gotify_url: str | None = None,
12
+ *,
13
+ app_name: str = "Django",
14
+ cooldown_seconds: int = 300,
15
+ max_request_body_size: str = "always",
16
+ **sentry_kwargs,
17
+ ) -> bool:
18
+ """Initialize sentry-sdk for Bugsink with Gotify push notifications."""
19
+ dsn = dsn or os.getenv("BUGSINK_DSN")
20
+ gotify_url = gotify_url or os.getenv("GOTIFY_URL")
21
+ if not dsn:
22
+ return False
23
+
24
+ parsed = urlparse(dsn)
25
+ domain = parsed.hostname or ""
26
+ project_id = parsed.path.strip("/").split("/")[-1]
27
+
28
+ if gotify_url and domain and project_id:
29
+ sentry_kwargs.setdefault(
30
+ "before_send",
31
+ gotify_handler(
32
+ gotify_url,
33
+ domain,
34
+ project_id,
35
+ app_name=app_name,
36
+ cooldown_seconds=cooldown_seconds,
37
+ ),
38
+ )
39
+
40
+ sentry_sdk.init(
41
+ dsn=dsn,
42
+ traces_sample_rate=0,
43
+ send_client_reports=False,
44
+ max_request_body_size=max_request_body_size,
45
+ **sentry_kwargs,
46
+ )
47
+ return True
48
+
49
+ __all__ = ["gotify_handler"]
gotisink/django.py ADDED
@@ -0,0 +1,117 @@
1
+ import json
2
+ import logging
3
+ import time
4
+ import urllib.error
5
+ import urllib.request
6
+ from importlib.metadata import PackageNotFoundError, version
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ def _get_user_agent() -> str:
12
+ try:
13
+ pkg_version = version("gotisink")
14
+ except PackageNotFoundError:
15
+ pkg_version = "dev"
16
+ return f"gotisink/{pkg_version}"
17
+
18
+
19
+ def _extract_error_summary(event: dict) -> str:
20
+ exc = event.get("exception")
21
+ if isinstance(exc, dict):
22
+ values = exc.get("values")
23
+ if isinstance(values, list):
24
+ for item in reversed(values):
25
+ if isinstance(item, dict) and item.get("type"):
26
+ exc_type = item["type"]
27
+ exc_value = item.get("value")
28
+ return (
29
+ f"{exc_type}: {exc_value}"
30
+ if exc_value
31
+ else str(exc_type)
32
+ )
33
+
34
+ logentry = event.get("logentry")
35
+ if isinstance(logentry, dict):
36
+ if logentry.get("formatted"):
37
+ return str(logentry["formatted"])
38
+ if logentry.get("message"):
39
+ return str(logentry["message"])
40
+
41
+ return str(event.get("message") or "Unhandled error")
42
+
43
+
44
+ def gotify_handler(
45
+ gotify_url: str,
46
+ bugsink_domain: str,
47
+ bugsink_project_id: str | int,
48
+ *,
49
+ app_name: str = "Django",
50
+ cooldown_seconds: int = 300,
51
+ timeout: float = 5.0,
52
+ ):
53
+ last_send_time = 0.0
54
+ clean_domain = (
55
+ bugsink_domain.removeprefix("https://")
56
+ .removeprefix("http://")
57
+ .rstrip("/")
58
+ )
59
+ bugsink_url = f"https://{clean_domain}/issues/{bugsink_project_id}/"
60
+
61
+ def before_send(event, hint):
62
+ nonlocal last_send_time
63
+ if not isinstance(event, dict):
64
+ return event
65
+
66
+ now = time.monotonic()
67
+ if now - last_send_time < cooldown_seconds:
68
+ return event
69
+
70
+ server_name = event.get("server_name") or ""
71
+ level = event.get("level") or "error"
72
+ summary = _extract_error_summary(event)
73
+
74
+ header = f"**Error in {app_name}**"
75
+ if server_name:
76
+ header = f"**Error in {app_name} ({server_name})**"
77
+
78
+ message_body = (
79
+ f"{header}\n"
80
+ f"Message: {summary}\n\n"
81
+ f"[Click here to view in Bugsink]({bugsink_url})"
82
+ )
83
+
84
+ payload = json.dumps(
85
+ {
86
+ "title": f"{app_name} Error: {level}",
87
+ "message": message_body,
88
+ "priority": 5,
89
+ "extras": {
90
+ "client::display": {"contentType": "text/markdown"},
91
+ },
92
+ }
93
+ ).encode("utf-8")
94
+
95
+ user_agent = _get_user_agent()
96
+ req = urllib.request.Request(
97
+ gotify_url,
98
+ data=payload,
99
+ headers={
100
+ "Content-Type": "application/json",
101
+ "User-Agent": user_agent,
102
+ },
103
+ method="POST",
104
+ )
105
+
106
+ try:
107
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
108
+ if 200 <= resp.status < 300:
109
+ last_send_time = now
110
+ else:
111
+ logger.warning("Gotify returned HTTP %s", resp.status)
112
+ except (urllib.error.URLError, TimeoutError, OSError) as exc:
113
+ logger.error("Error sending alert to Gotify: %s", exc)
114
+
115
+ return event
116
+
117
+ return before_send
@@ -0,0 +1,60 @@
1
+ Metadata-Version: 2.3
2
+ Name: gotisink
3
+ Version: 0.1.1
4
+ Summary: Send Bugsink/Sentry error alerts to Gotify.
5
+ Author: Xabi Bello
6
+ Author-email: Xabi Bello <xbello@gmail.com>
7
+ License: MIT
8
+ Requires-Dist: sentry-sdk>=3.0.1
9
+ Requires-Python: >=3.14
10
+ Project-URL: Homepage, https://gitlab.com/xbello/gotisink
11
+ Description-Content-Type: text/markdown
12
+
13
+ # gotisink
14
+
15
+ Send [Bugsink](https://www.bugsink.com/) (or Sentry) error alerts to [Gotify](https://gotify.net/) from Django with built-in cooldown throttling and minimal `settings.py` boilerplate.
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ pip install gotisink
21
+
22
+ export BUGSINK_DSN="https://<public_key>@bugs.example.com/1"
23
+ export GOTIFY_URL="https://gotify.example.com/message?<app_token>"
24
+ ```
25
+
26
+ Add the lines to settings.py:
27
+
28
+ import gotisink
29
+
30
+ gotisink.init(app_name="MyProject")
31
+
32
+ Automatically get the values from environment.
33
+
34
+ ## Configuration options
35
+
36
+ To further configure the stack, e.g. using a `.env` file and [Django environ](https://django-environ.readthedocs.io/en/latest/), change the parameters for the function call:
37
+
38
+ ```bash
39
+ $ cat .env
40
+ bugsink_dsn="https://<public_key>@bugsink.example.com/1"
41
+ gotify_url="https://gotify.example.com/message?token=<token>"
42
+ ```
43
+ `settings.py`:
44
+
45
+ import environ
46
+
47
+ ...
48
+ env = environ.Env()
49
+ ...
50
+
51
+ bugsink_dsn = env.get("bugsink_dsn")
52
+ gotify_url = env.get("gotify_url")
53
+
54
+ gotisink.init(
55
+ dsn=bugsink_dsn,
56
+ gotify_url=gotify_url,
57
+ app_name="MyProject", # shown in notification title & header
58
+ cooldown_seconds=300, # minimum seconds between Gotify alerts (default: 300)
59
+ max_request_body_size="always",
60
+ )
@@ -0,0 +1,5 @@
1
+ gotisink/__init__.py,sha256=80SO9CnuQ-n7L2u6AzMCkd3UWmAh_QOKM1BULqZE2qM,1215
2
+ gotisink/django.py,sha256=-15xtlA0yCxYY3RJyKNHXOt_a8mIO-kgJv1Y7ooTJtg,3416
3
+ gotisink-0.1.1.dist-info/WHEEL,sha256=-gI5GRFdiNNn2CFz-ptlExISMINC-k8bFxeojAlHbrM,81
4
+ gotisink-0.1.1.dist-info/METADATA,sha256=dx0v0cJ8-l45I9S8_dMAqPlhNarF0uJailtm4fpiJTk,1636
5
+ gotisink-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.10
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any