Debian Codegraph @

aws_xray_sdk/ext/requests/patch.py

raw
1 import wrapt
2
3 from aws_xray_sdk.core import xray_recorder
4 from aws_xray_sdk.core.models import http
5 from aws_xray_sdk.ext.util import inject_trace_header
6
7
8 def patch():
9
10 wrapt.wrap_function_wrapper(
11 'requests',
12 'Session.request',
13 _xray_traced_requests
14 )
15
16 wrapt.wrap_function_wrapper(
17 'requests',
18 'Session.prepare_request',
19 _inject_header
20 )
21
22
23 def _xray_traced_requests(wrapped, instance, args, kwargs):
24
25 url = kwargs.get('url') or args[1]
26
27 return xray_recorder.record_subsegment(
28 wrapped, instance, args, kwargs,
29 name=url,
30 namespace='remote',
31 meta_processor=requests_processor,
32 )
33
34
35 def _inject_header(wrapped, instance, args, kwargs):
36 request = args[0]
37 headers = getattr(request, 'headers', {})
38 inject_trace_header(headers, xray_recorder.current_subsegment())
39 setattr(request, 'headers', headers)
40
41 return wrapped(*args, **kwargs)
42
43
44 def requests_processor(wrapped, instance, args, kwargs,
45 return_value, exception, subsegment, stack):
46
47 method = kwargs.get('method') or args[0]
48 url = kwargs.get('url') or args[1]
49
50 subsegment.put_http_meta(http.METHOD, method)
51 subsegment.put_http_meta(http.URL, url)
52
53 if return_value is not None:
54 subsegment.put_http_meta(http.STATUS, return_value.status_code)
55 elif exception:
56 subsegment.add_exception(exception, stack)