feat(flask): Add `sentry_trace()` template helper (#1336) · gitcommit90/sentry-python@254b7e7 · GitHub
Skip to content

Commit 254b7e7

Browse files
authored
feat(flask): Add sentry_trace() template helper (getsentry#1336)
To setup distributed tracing links between a Flask app and a front-end app, one needs to figure out how to get the current hub, safely get the traceparent and then properly pass it into a template and then finally use that properly in a `meta` tag. [The guide](https://docs.sentry.io/platforms/javascript/performance/connect-services/) is woefully inadequete and error-prone so this PR adds a built-in helper `sentry_trace()` to the Flask integration to simplfy this linking.
1 parent 64577a7 commit 254b7e7

3 files changed

Lines changed: 63 additions & 11 deletions

File tree

examples/tracing/templates/index.html

Lines changed: 3 additions & 9 deletions

sentry_sdk/integrations/flask.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,15 @@
2727

2828
try:
2929
from flask import ( # type: ignore
30+
Markup,
3031
Request,
3132
Flask,
3233
_request_ctx_stack,
3334
_app_ctx_stack,
3435
__version__ as FLASK_VERSION,
3536
)
3637
from flask.signals import (
38+
before_render_template,
3739
got_request_exception,
3840
request_started,
3941
)
@@ -77,6 +79,7 @@ def setup_once():
7779
if version < (0, 10):
7880
raise DidNotEnable("Flask 0.10 or newer is required.")
7981

82+
before_render_template.connect(_add_sentry_trace)
8083
request_started.connect(_request_started)
8184
got_request_exception.connect(_capture_exception)
8285

@@ -94,6 +97,23 @@ def sentry_patched_wsgi_app(self, environ, start_response):
9497
Flask.__call__ = sentry_patched_wsgi_app # type: ignore
9598

9699

100+
def _add_sentry_trace(sender, template, context, **extra):
101+
# type: (Flask, Any, Dict[str, Any], **Any) -> None
102+
103+
if "sentry_trace" in context:
104+
return
105+
106+
sentry_span = Hub.current.scope.span
107+
context["sentry_trace"] = (
108+
Markup(
109+
'<meta name="sentry-trace" content="%s" />'
110+
% (sentry_span.to_traceparent(),)
111+
)
112+
if sentry_span
113+
else ""
114+
)
115+
116+
97117
def _request_started(sender, **kwargs):
98118
# type: (Flask, **Any) -> None
99119
hub = Hub.current

tests/integrations/flask/test_flask.py

Lines changed: 40 additions & 2 deletions

0 commit comments

Comments
 (0)