Skip to content

Instantly share code, notes, and snippets.

@n1ckdm
Last active November 5, 2021 15:38
Show Gist options
  • Save n1ckdm/5e274cf57f2ae3f70e8c3e005581ace0 to your computer and use it in GitHub Desktop.
Save n1ckdm/5e274cf57f2ae3f70e8c3e005581ace0 to your computer and use it in GitHub Desktop.
Context manager that yeilds a requests session and starts a span that already has the headers injected with the span's context so that this is passed into the request for tracing
import requests
from typing import Generator
from contextlib import contextmanager
from dataclasses import dataclass
@dataclass
class Context:
span: opentracing.Span
session: requests.Session
@contextmanager
def make_traced_request(url: str) -> Generator[Context]:
"""
Yeilds a requests session and starts a span that already has the
headers injected with the span's context so that this is passed
into the request for tracing
"""
with opentracing.tracer.start_active_span(url) as scope:
session = requests.session()
headers = {}
opentracing.tracer.inject(
scope.span,
opentracing.Format.HTTP_HEADERS,
headers
)
session.headers.update(headers)
yield Context(scope.span, session)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment