From 17c130a6cc4e66bb17b9232125bb4e35778abe45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20K=C3=A4ufl?= Date: Tue, 4 Apr 2023 10:21:23 +0200 Subject: [PATCH 1/8] Remove unused config for Travis CI --- .travis.yml | 26 -------------------------- 1 file changed, 26 deletions(-) delete mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 2970fcde..00000000 --- a/.travis.yml +++ /dev/null @@ -1,26 +0,0 @@ -language: python -dist: xenial -python: - - "2.7" - - "3.4" - - "3.5" - - "3.6" - - "3.7" - - "3.8" - - "3.9" - -addons: - postgresql: "9.6" - -install: - - pip install tox tox-travis - -notifications: - email: - recipients: - - aws-xray-peryton@amazon.com - on_success: never - on_failure: always - -script: - - tox From 67a42271f6ad820f67ccd6d10ff0edc5f3576595 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20K=C3=A4ufl?= Date: Tue, 4 Apr 2023 10:22:17 +0200 Subject: [PATCH 2/8] Remove classifiers for unsupported Python versions --- setup.py | 5 ----- 1 file changed, 5 deletions(-) diff --git a/setup.py b/setup.py index 4b1df155..fc5be94f 100644 --- a/setup.py +++ b/setup.py @@ -28,12 +28,7 @@ 'Natural Language :: English', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python', - 'Programming Language :: Python :: 2', - 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.4', - 'Programming Language :: Python :: 3.5', - 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', From e6e4b9f1599968278a96569080ce477a4731f5eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20K=C3=A4ufl?= Date: Tue, 4 Apr 2023 10:23:35 +0200 Subject: [PATCH 3/8] Add `python_requires` and remove unused dependencies --- setup.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/setup.py b/setup.py index fc5be94f..2318c29e 100644 --- a/setup.py +++ b/setup.py @@ -36,10 +36,9 @@ 'Programming Language :: Python :: 3.11', ], + python_requires=">=3.7", install_requires=[ - 'enum34;python_version<"3.4"', 'wrapt', - 'future;python_version<"3"', 'botocore>=1.11.3', ], From 678cac98e422ec4e93a1c2658cf05463fbfd56d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20K=C3=A4ufl?= Date: Tue, 4 Apr 2023 10:45:16 +0200 Subject: [PATCH 4/8] Use Python 3 style `super()` calls --- aws_xray_sdk/core/async_context.py | 2 +- aws_xray_sdk/core/models/dummy_entities.py | 6 +++--- aws_xray_sdk/core/models/facade_segment.py | 2 +- aws_xray_sdk/core/models/segment.py | 10 +++++----- aws_xray_sdk/core/models/subsegment.py | 10 +++++----- aws_xray_sdk/ext/dbapi2.py | 4 ++-- aws_xray_sdk/ext/django/db.py | 6 +++--- aws_xray_sdk/ext/pymongo/patch.py | 2 +- tests/ext/aiohttp/test_middleware.py | 2 +- tests/mock_module/mock_submodule/mock_subfile.py | 2 +- tests/test_serialize_entities.py | 2 +- tests/util.py | 2 +- 12 files changed, 25 insertions(+), 25 deletions(-) diff --git a/aws_xray_sdk/core/async_context.py b/aws_xray_sdk/core/async_context.py index acba00e2..057a9265 100644 --- a/aws_xray_sdk/core/async_context.py +++ b/aws_xray_sdk/core/async_context.py @@ -16,7 +16,7 @@ class AsyncContext(_Context): Also overrides clear_trace_entities """ def __init__(self, *args, loop=None, use_task_factory=True, **kwargs): - super(AsyncContext, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self._loop = loop if loop is None: diff --git a/aws_xray_sdk/core/models/dummy_entities.py b/aws_xray_sdk/core/models/dummy_entities.py index 6d962d71..78eea9c4 100644 --- a/aws_xray_sdk/core/models/dummy_entities.py +++ b/aws_xray_sdk/core/models/dummy_entities.py @@ -18,9 +18,9 @@ class DummySegment(Segment): def __init__(self, name='dummy'): no_op_id = os.getenv('AWS_XRAY_NOOP_ID') if no_op_id and no_op_id.lower() == 'false': - super(DummySegment, self).__init__(name=name, traceid=TraceId().to_id()) + super().__init__(name=name, traceid=TraceId().to_id()) else: - super(DummySegment, self).__init__(name=name, traceid=NoOpTraceId().to_id(), entityid='0000000000000000') + super().__init__(name=name, traceid=NoOpTraceId().to_id(), entityid='0000000000000000') self.sampled = False def set_aws(self, aws_meta): @@ -87,7 +87,7 @@ class DummySubsegment(Subsegment): """ def __init__(self, segment, name='dummy'): - super(DummySubsegment, self).__init__(name, 'dummy', segment) + super().__init__(name, 'dummy', segment) no_op_id = os.getenv('AWS_XRAY_NOOP_ID') if no_op_id and no_op_id.lower() == 'false': super(Subsegment, self).__init__(name) diff --git a/aws_xray_sdk/core/models/facade_segment.py b/aws_xray_sdk/core/models/facade_segment.py index 545a914a..5f16aba5 100644 --- a/aws_xray_sdk/core/models/facade_segment.py +++ b/aws_xray_sdk/core/models/facade_segment.py @@ -22,7 +22,7 @@ def __init__(self, name, entityid, traceid, sampled): sampled=sampled, ) - super(FacadeSegment, self).__init__( + super().__init__( name=name, entityid=entityid, traceid=traceid, diff --git a/aws_xray_sdk/core/models/segment.py b/aws_xray_sdk/core/models/segment.py index ce6ca8b7..b26dc1ab 100644 --- a/aws_xray_sdk/core/models/segment.py +++ b/aws_xray_sdk/core/models/segment.py @@ -63,7 +63,7 @@ def __init__(self, name, entityid=None, traceid=None, if not name: raise SegmentNameMissingException("Segment name is required.") - super(Segment, self).__init__(name) + super().__init__(name) if not traceid: traceid = TraceId().to_id() @@ -85,7 +85,7 @@ def add_subsegment(self, subsegment): Add input subsegment as a child subsegment and increment reference counter and total subsegments counter. """ - super(Segment, self).add_subsegment(subsegment) + super().add_subsegment(subsegment) self.increment() def increment(self): @@ -127,7 +127,7 @@ def remove_subsegment(self, subsegment): """ Remove the reference of input subsegment. """ - super(Segment, self).remove_subsegment(subsegment) + super().remove_subsegment(subsegment) self.decrement_subsegments_size() def set_user(self, user): @@ -135,7 +135,7 @@ def set_user(self, user): set user of a segment. One segment can only have one user. User is indexed and can be later queried. """ - super(Segment, self)._check_ended() + super()._check_ended() self.user = user def set_service(self, service_info): @@ -160,7 +160,7 @@ def to_dict(self): Convert Segment object to dict with required properties that have non-empty values. """ - segment_dict = super(Segment, self).to_dict() + segment_dict = super().to_dict() del segment_dict['ref_counter'] del segment_dict['_subsegments_counter'] diff --git a/aws_xray_sdk/core/models/subsegment.py b/aws_xray_sdk/core/models/subsegment.py index 6737d18d..3c4289e9 100644 --- a/aws_xray_sdk/core/models/subsegment.py +++ b/aws_xray_sdk/core/models/subsegment.py @@ -95,7 +95,7 @@ def __init__(self, name, namespace, segment): support `aws`, `remote` and `local`. :param Segment segment: The parent segment """ - super(Subsegment, self).__init__(name) + super().__init__(name) if not segment: raise SegmentNotFoundException("A parent segment is required for creating subsegments.") @@ -114,7 +114,7 @@ def add_subsegment(self, subsegment): reference counter and total subsegments counter of the parent segment. """ - super(Subsegment, self).add_subsegment(subsegment) + super().add_subsegment(subsegment) self.parent_segment.increment() def remove_subsegment(self, subsegment): @@ -124,7 +124,7 @@ def remove_subsegment(self, subsegment): :param Subsegment: subsegment to remove. """ - super(Subsegment, self).remove_subsegment(subsegment) + super().remove_subsegment(subsegment) self.parent_segment.decrement_subsegments_size() def close(self, end_time=None): @@ -136,7 +136,7 @@ def close(self, end_time=None): :param int end_time: Epoch in seconds. If not specified current time will be used. """ - super(Subsegment, self).close(end_time) + super().close(end_time) self.parent_segment.decrement_ref_counter() def set_sql(self, sql): @@ -154,7 +154,7 @@ def to_dict(self): Convert Subsegment object to dict with required properties that have non-empty values. """ - subsegment_dict = super(Subsegment, self).to_dict() + subsegment_dict = super().to_dict() del subsegment_dict['parent_segment'] diff --git a/aws_xray_sdk/ext/dbapi2.py b/aws_xray_sdk/ext/dbapi2.py index c3ed8241..3db4f44f 100644 --- a/aws_xray_sdk/ext/dbapi2.py +++ b/aws_xray_sdk/ext/dbapi2.py @@ -10,7 +10,7 @@ class XRayTracedConn(wrapt.ObjectProxy): def __init__(self, conn, meta={}): - super(XRayTracedConn, self).__init__(conn) + super().__init__(conn) self._xray_meta = meta def cursor(self, *args, **kwargs): @@ -25,7 +25,7 @@ class XRayTracedCursor(wrapt.ObjectProxy): def __init__(self, cursor, meta={}): - super(XRayTracedCursor, self).__init__(cursor) + super().__init__(cursor) self._xray_meta = meta # we preset database type if db is framework built-in diff --git a/aws_xray_sdk/ext/django/db.py b/aws_xray_sdk/ext/django/db.py index fdf7e27a..9106de58 100644 --- a/aws_xray_sdk/ext/django/db.py +++ b/aws_xray_sdk/ext/django/db.py @@ -21,7 +21,7 @@ def execute(self, query, *args, **kwargs): if xray_recorder.stream_sql: _previous_meta = copy.copy(self._xray_meta) self._xray_meta['sanitized_query'] = query - result = super(DjangoXRayTracedCursor, self).execute(query, *args, **kwargs) + result = super().execute(query, *args, **kwargs) if xray_recorder.stream_sql: self._xray_meta = _previous_meta return result @@ -30,7 +30,7 @@ def executemany(self, query, *args, **kwargs): if xray_recorder.stream_sql: _previous_meta = copy.copy(self._xray_meta) self._xray_meta['sanitized_query'] = query - result = super(DjangoXRayTracedCursor, self).executemany(query, *args, **kwargs) + result = super().executemany(query, *args, **kwargs) if xray_recorder.stream_sql: self._xray_meta = _previous_meta return result @@ -39,7 +39,7 @@ def callproc(self, proc, args): if xray_recorder.stream_sql: _previous_meta = copy.copy(self._xray_meta) self._xray_meta['sanitized_query'] = proc - result = super(DjangoXRayTracedCursor, self).callproc(proc, args) + result = super().callproc(proc, args) if xray_recorder.stream_sql: self._xray_meta = _previous_meta return result diff --git a/aws_xray_sdk/ext/pymongo/patch.py b/aws_xray_sdk/ext/pymongo/patch.py index 4d8cc1a4..cd8df5d9 100644 --- a/aws_xray_sdk/ext/pymongo/patch.py +++ b/aws_xray_sdk/ext/pymongo/patch.py @@ -15,7 +15,7 @@ class XrayCommandListener(monitoring.CommandListener): """ def __init__(self, record_full_documents): - super(XrayCommandListener, self).__init__() + super().__init__() self.record_full_documents = record_full_documents def started(self, event): diff --git a/tests/ext/aiohttp/test_middleware.py b/tests/ext/aiohttp/test_middleware.py index 025af6a1..45c07121 100644 --- a/tests/ext/aiohttp/test_middleware.py +++ b/tests/ext/aiohttp/test_middleware.py @@ -29,7 +29,7 @@ class CustomStubbedEmitter(UDPEmitter): """ def __init__(self, daemon_address='127.0.0.1:2000'): - super(CustomStubbedEmitter, self).__init__(daemon_address) + super().__init__(daemon_address) self.local = [] def send_entity(self, entity): diff --git a/tests/mock_module/mock_submodule/mock_subfile.py b/tests/mock_module/mock_submodule/mock_subfile.py index 840f96fd..866131aa 100644 --- a/tests/mock_module/mock_submodule/mock_subfile.py +++ b/tests/mock_module/mock_submodule/mock_subfile.py @@ -29,7 +29,7 @@ def mock_staticmethod(): class MockSubclass(MockClass): def __init__(self): - super(MockSubclass, self).__init__() + super().__init__() def mock_submethod(self): pass diff --git a/tests/test_serialize_entities.py b/tests/test_serialize_entities.py index d46d737b..f3a041a6 100644 --- a/tests/test_serialize_entities.py +++ b/tests/test_serialize_entities.py @@ -258,7 +258,7 @@ def test_serialize_segment_with_exception(): class TestException(Exception): def __init__(self, message): - super(TestException, self).__init__(message) + super().__init__(message) segment_one = Segment('test') diff --git a/tests/util.py b/tests/util.py index 074e712d..2510b0b7 100644 --- a/tests/util.py +++ b/tests/util.py @@ -10,7 +10,7 @@ class StubbedEmitter(UDPEmitter): def __init__(self, daemon_address='127.0.0.1:2000'): - super(StubbedEmitter, self).__init__(daemon_address) + super().__init__(daemon_address) self._local = threading.local() def send_entity(self, entity): From f519826620707c2ae52b4d25f8eb52a10c429926 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20K=C3=A4ufl?= Date: Tue, 4 Apr 2023 10:47:49 +0200 Subject: [PATCH 5/8] =?UTF-8?q?Use=20=E2=80=9Cnew=20style=E2=80=9D=20class?= =?UTF-8?q?es?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Stop inheriting from object explicitly --- aws_xray_sdk/core/async_context.py | 2 +- aws_xray_sdk/core/context.py | 2 +- aws_xray_sdk/core/daemon_config.py | 2 +- aws_xray_sdk/core/emitters/udp_emitter.py | 2 +- aws_xray_sdk/core/models/default_dynamic_naming.py | 2 +- aws_xray_sdk/core/models/entity.py | 2 +- aws_xray_sdk/core/models/throwable.py | 2 +- aws_xray_sdk/core/models/trace_header.py | 2 +- aws_xray_sdk/core/recorder.py | 2 +- aws_xray_sdk/core/sampling/connector.py | 2 +- aws_xray_sdk/core/sampling/local/reservoir.py | 2 +- aws_xray_sdk/core/sampling/local/sampler.py | 2 +- aws_xray_sdk/core/sampling/local/sampling_rule.py | 2 +- aws_xray_sdk/core/sampling/reservoir.py | 2 +- aws_xray_sdk/core/sampling/rule_cache.py | 2 +- aws_xray_sdk/core/sampling/rule_poller.py | 2 +- aws_xray_sdk/core/sampling/sampler.py | 2 +- aws_xray_sdk/core/sampling/sampling_rule.py | 2 +- aws_xray_sdk/core/sampling/target_poller.py | 2 +- aws_xray_sdk/core/streaming/default_streaming.py | 2 +- aws_xray_sdk/core/utils/atomic_counter.py | 2 +- aws_xray_sdk/ext/bottle/middleware.py | 2 +- aws_xray_sdk/ext/django/conf.py | 2 +- aws_xray_sdk/ext/django/middleware.py | 2 +- aws_xray_sdk/ext/flask/middleware.py | 2 +- aws_xray_sdk/sdk_config.py | 2 +- tests/ext/aiohttp/test_middleware.py | 2 +- tests/ext/pynamodb/test_pynamodb.py | 2 +- tests/mock_module/mock_submodule/mock_subfile.py | 2 +- 29 files changed, 29 insertions(+), 29 deletions(-) diff --git a/aws_xray_sdk/core/async_context.py b/aws_xray_sdk/core/async_context.py index 057a9265..092aeda0 100644 --- a/aws_xray_sdk/core/async_context.py +++ b/aws_xray_sdk/core/async_context.py @@ -35,7 +35,7 @@ def clear_trace_entities(self): self._local.clear() -class TaskLocalStorage(object): +class TaskLocalStorage: """ Simple task local storage """ diff --git a/aws_xray_sdk/core/context.py b/aws_xray_sdk/core/context.py index 4b4f08b4..63e994de 100644 --- a/aws_xray_sdk/core/context.py +++ b/aws_xray_sdk/core/context.py @@ -14,7 +14,7 @@ CXT_MISSING_STRATEGY_KEY = 'AWS_XRAY_CONTEXT_MISSING' -class Context(object): +class Context: """ The context storage class to store trace entities(segments/subsegments). The default implementation uses threadlocal to store these entities. diff --git a/aws_xray_sdk/core/daemon_config.py b/aws_xray_sdk/core/daemon_config.py index 34b66a37..0331d052 100644 --- a/aws_xray_sdk/core/daemon_config.py +++ b/aws_xray_sdk/core/daemon_config.py @@ -6,7 +6,7 @@ DEFAULT_ADDRESS = '127.0.0.1:2000' -class DaemonConfig(object): +class DaemonConfig: """The class that stores X-Ray daemon configuration about the ip address and port for UDP and TCP port. It gets the address string from ``AWS_TRACING_DAEMON_ADDRESS`` and then from recorder's diff --git a/aws_xray_sdk/core/emitters/udp_emitter.py b/aws_xray_sdk/core/emitters/udp_emitter.py index 03785a2e..16e1e509 100644 --- a/aws_xray_sdk/core/emitters/udp_emitter.py +++ b/aws_xray_sdk/core/emitters/udp_emitter.py @@ -12,7 +12,7 @@ DEFAULT_DAEMON_ADDRESS = '127.0.0.1:2000' -class UDPEmitter(object): +class UDPEmitter: """ The default emitter the X-Ray recorder uses to send segments/subsegments to the X-Ray daemon over UDP using a non-blocking socket. If there is an diff --git a/aws_xray_sdk/core/models/default_dynamic_naming.py b/aws_xray_sdk/core/models/default_dynamic_naming.py index ff417736..343acc4a 100644 --- a/aws_xray_sdk/core/models/default_dynamic_naming.py +++ b/aws_xray_sdk/core/models/default_dynamic_naming.py @@ -1,7 +1,7 @@ from ..utils.search_pattern import wildcard_match -class DefaultDynamicNaming(object): +class DefaultDynamicNaming: """ Decides what name to use on a segment generated from an incoming request. By default it takes the host name and compares it to a pre-defined pattern. diff --git a/aws_xray_sdk/core/models/entity.py b/aws_xray_sdk/core/models/entity.py index 3583bf28..12663b1d 100644 --- a/aws_xray_sdk/core/models/entity.py +++ b/aws_xray_sdk/core/models/entity.py @@ -21,7 +21,7 @@ ORIGIN_TRACE_HEADER_ATTR_KEY = '_origin_trace_header' -class Entity(object): +class Entity: """ The parent class for segment/subsegment. It holds common properties and methods on segment and subsegment. diff --git a/aws_xray_sdk/core/models/throwable.py b/aws_xray_sdk/core/models/throwable.py index 43f76b7c..4d92942a 100644 --- a/aws_xray_sdk/core/models/throwable.py +++ b/aws_xray_sdk/core/models/throwable.py @@ -8,7 +8,7 @@ log = logging.getLogger(__name__) -class Throwable(object): +class Throwable: """ An object recording exception infomation under trace entity `cause` section. The information includes the stack trace, diff --git a/aws_xray_sdk/core/models/trace_header.py b/aws_xray_sdk/core/models/trace_header.py index b15fb8a7..b00c19cd 100644 --- a/aws_xray_sdk/core/models/trace_header.py +++ b/aws_xray_sdk/core/models/trace_header.py @@ -10,7 +10,7 @@ HEADER_DELIMITER = ";" -class TraceHeader(object): +class TraceHeader: """ The sampling decision and trace ID are added to HTTP requests in tracing headers named ``X-Amzn-Trace-Id``. The first X-Ray-integrated diff --git a/aws_xray_sdk/core/recorder.py b/aws_xray_sdk/core/recorder.py index 1710fb40..09cba247 100644 --- a/aws_xray_sdk/core/recorder.py +++ b/aws_xray_sdk/core/recorder.py @@ -40,7 +40,7 @@ } -class AWSXRayRecorder(object): +class AWSXRayRecorder: """ A global AWS X-Ray recorder that will begin/end segments/subsegments and send them to the X-Ray daemon. This recorder is initialized during diff --git a/aws_xray_sdk/core/sampling/connector.py b/aws_xray_sdk/core/sampling/connector.py index b8e288fe..433d8405 100644 --- a/aws_xray_sdk/core/sampling/connector.py +++ b/aws_xray_sdk/core/sampling/connector.py @@ -13,7 +13,7 @@ from aws_xray_sdk.core.utils.compat import PY2 -class ServiceConnector(object): +class ServiceConnector: """ Connector class that translates Centralized Sampling poller functions to actual X-Ray back-end APIs and communicates with X-Ray daemon as the diff --git a/aws_xray_sdk/core/sampling/local/reservoir.py b/aws_xray_sdk/core/sampling/local/reservoir.py index ac65d741..2be7bc6f 100644 --- a/aws_xray_sdk/core/sampling/local/reservoir.py +++ b/aws_xray_sdk/core/sampling/local/reservoir.py @@ -2,7 +2,7 @@ import threading -class Reservoir(object): +class Reservoir: """ Keeps track of the number of sampled segments within a single second. This class is implemented to be diff --git a/aws_xray_sdk/core/sampling/local/sampler.py b/aws_xray_sdk/core/sampling/local/sampler.py index ebc09413..1db0163a 100644 --- a/aws_xray_sdk/core/sampling/local/sampler.py +++ b/aws_xray_sdk/core/sampling/local/sampler.py @@ -11,7 +11,7 @@ SUPPORTED_RULE_VERSION = (1, 2) -class LocalSampler(object): +class LocalSampler: """ The local sampler that holds either custom sampling rules or default sampling rules defined locally. The X-Ray recorder diff --git a/aws_xray_sdk/core/sampling/local/sampling_rule.py b/aws_xray_sdk/core/sampling/local/sampling_rule.py index 7d0a5dcb..adc0fdf5 100644 --- a/aws_xray_sdk/core/sampling/local/sampling_rule.py +++ b/aws_xray_sdk/core/sampling/local/sampling_rule.py @@ -3,7 +3,7 @@ from aws_xray_sdk.core.utils.search_pattern import wildcard_match -class SamplingRule(object): +class SamplingRule: """ One SamolingRule represents one rule defined from local rule json file or from a dictionary. It can be either a custom rule or default rule. diff --git a/aws_xray_sdk/core/sampling/reservoir.py b/aws_xray_sdk/core/sampling/reservoir.py index 14188b34..d542fe30 100644 --- a/aws_xray_sdk/core/sampling/reservoir.py +++ b/aws_xray_sdk/core/sampling/reservoir.py @@ -2,7 +2,7 @@ from enum import Enum -class Reservoir(object): +class Reservoir: """ Centralized thread-safe reservoir which holds fixed sampling quota, borrowed count and TTL. diff --git a/aws_xray_sdk/core/sampling/rule_cache.py b/aws_xray_sdk/core/sampling/rule_cache.py index 2cec5190..fca9df62 100644 --- a/aws_xray_sdk/core/sampling/rule_cache.py +++ b/aws_xray_sdk/core/sampling/rule_cache.py @@ -4,7 +4,7 @@ TTL = 60 * 60 # The cache expires 1 hour after the last refresh time. -class RuleCache(object): +class RuleCache: """ Cache sampling rules and quota retrieved by ``TargetPoller`` and ``RulePoller``. It will not return anything if it expires. diff --git a/aws_xray_sdk/core/sampling/rule_poller.py b/aws_xray_sdk/core/sampling/rule_poller.py index 301e04b0..07758766 100644 --- a/aws_xray_sdk/core/sampling/rule_poller.py +++ b/aws_xray_sdk/core/sampling/rule_poller.py @@ -8,7 +8,7 @@ DEFAULT_INTERVAL = 5 * 60 # 5 minutes on sampling rules fetch -class RulePoller(object): +class RulePoller: def __init__(self, cache, connector): diff --git a/aws_xray_sdk/core/sampling/sampler.py b/aws_xray_sdk/core/sampling/sampler.py index 8c09d59b..b793dd20 100644 --- a/aws_xray_sdk/core/sampling/sampler.py +++ b/aws_xray_sdk/core/sampling/sampler.py @@ -14,7 +14,7 @@ log = logging.getLogger(__name__) -class DefaultSampler(object): +class DefaultSampler: """Making sampling decisions based on centralized sampling rules defined by X-Ray control plane APIs. It will fall back to local sampler if centralized sampling rules are not available. diff --git a/aws_xray_sdk/core/sampling/sampling_rule.py b/aws_xray_sdk/core/sampling/sampling_rule.py index fb4c6508..9dbe55b1 100644 --- a/aws_xray_sdk/core/sampling/sampling_rule.py +++ b/aws_xray_sdk/core/sampling/sampling_rule.py @@ -4,7 +4,7 @@ from aws_xray_sdk.core.utils.search_pattern import wildcard_match -class SamplingRule(object): +class SamplingRule: """ Data model for a single centralized sampling rule definition. """ diff --git a/aws_xray_sdk/core/sampling/target_poller.py b/aws_xray_sdk/core/sampling/target_poller.py index 2d4f7574..3a233805 100644 --- a/aws_xray_sdk/core/sampling/target_poller.py +++ b/aws_xray_sdk/core/sampling/target_poller.py @@ -6,7 +6,7 @@ log = logging.getLogger(__name__) -class TargetPoller(object): +class TargetPoller: """ The poller to report the current statistics of all centralized sampling rules and retrieve the new allocated diff --git a/aws_xray_sdk/core/streaming/default_streaming.py b/aws_xray_sdk/core/streaming/default_streaming.py index 1e02ed7b..6c23ddaf 100644 --- a/aws_xray_sdk/core/streaming/default_streaming.py +++ b/aws_xray_sdk/core/streaming/default_streaming.py @@ -1,7 +1,7 @@ import threading -class DefaultStreaming(object): +class DefaultStreaming: """ The default streaming strategy. It uses the total count of a segment's children subsegments as a threshold. If the threshold is diff --git a/aws_xray_sdk/core/utils/atomic_counter.py b/aws_xray_sdk/core/utils/atomic_counter.py index 5dfe14d7..4a3e54ee 100644 --- a/aws_xray_sdk/core/utils/atomic_counter.py +++ b/aws_xray_sdk/core/utils/atomic_counter.py @@ -1,7 +1,7 @@ import threading -class AtomicCounter(object): +class AtomicCounter: """ A helper class that implements a thread-safe counter. """ diff --git a/aws_xray_sdk/ext/bottle/middleware.py b/aws_xray_sdk/ext/bottle/middleware.py index f51d9ca0..706cf303 100644 --- a/aws_xray_sdk/ext/bottle/middleware.py +++ b/aws_xray_sdk/ext/bottle/middleware.py @@ -7,7 +7,7 @@ calculate_segment_name, construct_xray_header, prepare_response_header -class XRayMiddleware(object): +class XRayMiddleware: """ Middleware that wraps each incoming request to a segment. """ diff --git a/aws_xray_sdk/ext/django/conf.py b/aws_xray_sdk/ext/django/conf.py index 091968e2..42f0b266 100644 --- a/aws_xray_sdk/ext/django/conf.py +++ b/aws_xray_sdk/ext/django/conf.py @@ -30,7 +30,7 @@ ) -class XRaySettings(object): +class XRaySettings: """ A object of Django settings to easily modify certain fields. The precedence for configurations at different places is as follows: diff --git a/aws_xray_sdk/ext/django/middleware.py b/aws_xray_sdk/ext/django/middleware.py index d565be61..3c15bd33 100644 --- a/aws_xray_sdk/ext/django/middleware.py +++ b/aws_xray_sdk/ext/django/middleware.py @@ -19,7 +19,7 @@ CONTENT_LENGTH_KEY = 'content-length' -class XRayMiddleware(object): +class XRayMiddleware: """ Middleware that wraps each incoming request to a segment. """ diff --git a/aws_xray_sdk/ext/flask/middleware.py b/aws_xray_sdk/ext/flask/middleware.py index c0c1e226..fdc3b32f 100644 --- a/aws_xray_sdk/ext/flask/middleware.py +++ b/aws_xray_sdk/ext/flask/middleware.py @@ -8,7 +8,7 @@ from aws_xray_sdk.core.lambda_launcher import check_in_lambda, LambdaContext -class XRayMiddleware(object): +class XRayMiddleware: def __init__(self, app, recorder): self.app = app diff --git a/aws_xray_sdk/sdk_config.py b/aws_xray_sdk/sdk_config.py index 33a8e495..6078c761 100644 --- a/aws_xray_sdk/sdk_config.py +++ b/aws_xray_sdk/sdk_config.py @@ -4,7 +4,7 @@ log = logging.getLogger(__name__) -class SDKConfig(object): +class SDKConfig: """ Global Configuration Class that defines SDK-level configuration properties. diff --git a/tests/ext/aiohttp/test_middleware.py b/tests/ext/aiohttp/test_middleware.py index 45c07121..9055cd55 100644 --- a/tests/ext/aiohttp/test_middleware.py +++ b/tests/ext/aiohttp/test_middleware.py @@ -42,7 +42,7 @@ def pop(self): return None -class ServerTest(object): +class ServerTest: """ Simple class to hold a copy of the event loop """ diff --git a/tests/ext/pynamodb/test_pynamodb.py b/tests/ext/pynamodb/test_pynamodb.py index f1db1b37..d915a25a 100644 --- a/tests/ext/pynamodb/test_pynamodb.py +++ b/tests/ext/pynamodb/test_pynamodb.py @@ -58,7 +58,7 @@ def test_empty_response(): from aws_xray_sdk.ext.pynamodb.patch import pynamodb_meta_processor subsegment = xray_recorder.begin_subsegment('test') - class TempReq(object): + class TempReq: def __init__(self): self.headers = {'X-Amz-Target': 'ddb.ListTables'.encode('utf-8')} self.url = 'ddb.us-west-2' diff --git a/tests/mock_module/mock_submodule/mock_subfile.py b/tests/mock_module/mock_submodule/mock_subfile.py index 866131aa..7eb13b78 100644 --- a/tests/mock_module/mock_submodule/mock_subfile.py +++ b/tests/mock_module/mock_submodule/mock_subfile.py @@ -10,7 +10,7 @@ def mock_no_doublepatch(): pass -class MockClass(object): +class MockClass: def __init__(self): pass From f1760125d394fd3bce788cfef3fc7b9eb9432582 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20K=C3=A4ufl?= Date: Tue, 4 Apr 2023 11:06:15 +0200 Subject: [PATCH 6/8] Remove compatibility code for Python < 3.7 --- aws_xray_sdk/core/__init__.py | 11 +++----- aws_xray_sdk/core/async_context.py | 23 +++-------------- aws_xray_sdk/core/patcher.py | 21 +++++++--------- aws_xray_sdk/core/plugins/ec2_plugin.py | 9 +------ aws_xray_sdk/core/sampling/connector.py | 13 ++-------- aws_xray_sdk/core/utils/compat.py | 13 ++-------- aws_xray_sdk/ext/httplib/patch.py | 25 ++++++------------- .../ext/sqlalchemy/util/decorators.py | 12 +++------ aws_xray_sdk/ext/sqlalchemy_core/patch.py | 9 ++----- aws_xray_sdk/ext/util.py | 12 +++------ tests/ext/aiohttp/test_middleware.py | 14 ++++------- tests/ext/django/test_settings.py | 12 +++------ tests/ext/httplib/test_httplib.py | 19 +++++--------- tests/test_plugins.py | 7 ++---- tests/test_trace_entities.py | 10 +++----- tests/util.py | 12 +++------ 16 files changed, 60 insertions(+), 162 deletions(-) diff --git a/aws_xray_sdk/core/__init__.py b/aws_xray_sdk/core/__init__.py index cb94eed9..8abbe449 100644 --- a/aws_xray_sdk/core/__init__.py +++ b/aws_xray_sdk/core/__init__.py @@ -1,13 +1,8 @@ +from .async_recorder import AsyncAWSXRayRecorder +from .patcher import patch, patch_all from .recorder import AWSXRayRecorder -from .patcher import patch_all, patch -from .utils.compat import PY35 - -if not PY35: - xray_recorder = AWSXRayRecorder() -else: - from .async_recorder import AsyncAWSXRayRecorder - xray_recorder = AsyncAWSXRayRecorder() +xray_recorder = AsyncAWSXRayRecorder() __all__ = [ 'patch', diff --git a/aws_xray_sdk/core/async_context.py b/aws_xray_sdk/core/async_context.py index 092aeda0..59d92d50 100644 --- a/aws_xray_sdk/core/async_context.py +++ b/aws_xray_sdk/core/async_context.py @@ -1,11 +1,8 @@ import asyncio -import sys import copy from .context import Context as _Context -_GTE_PY37 = sys.version_info.major == 3 and sys.version_info.minor >= 7 - class AsyncContext(_Context): """ @@ -51,10 +48,7 @@ def __setattr__(self, name, value): else: # Set task local attributes - if _GTE_PY37: - task = asyncio.current_task(loop=self._loop) - else: - task = asyncio.Task.current_task(loop=self._loop) + task = asyncio.current_task(loop=self._loop) if task is None: return None @@ -68,10 +62,7 @@ def __getattribute__(self, item): # Return references to local objects return object.__getattribute__(self, item) - if _GTE_PY37: - task = asyncio.current_task(loop=self._loop) - else: - task = asyncio.Task.current_task(loop=self._loop) + task = asyncio.current_task(loop=self._loop) if task is None: return None @@ -82,10 +73,7 @@ def __getattribute__(self, item): def clear(self): # If were in a task, clear the context dictionary - if _GTE_PY37: - task = asyncio.current_task(loop=self._loop) - else: - task = asyncio.Task.current_task(loop=self._loop) + task = asyncio.current_task(loop=self._loop) if task is not None and hasattr(task, 'context'): task.context.clear() @@ -104,10 +92,7 @@ def task_factory(loop, coro): del task._source_traceback[-1] # flake8: noqa # Share context with new task if possible - if _GTE_PY37: - current_task = asyncio.current_task(loop=loop) - else: - current_task = asyncio.Task.current_task(loop=loop) + current_task = asyncio.current_task(loop=loop) if current_task is not None and hasattr(current_task, 'context'): if current_task.context.get('entities'): # NOTE: (enowell) Because the `AWSXRayRecorder`'s `Context` decides diff --git a/aws_xray_sdk/core/patcher.py b/aws_xray_sdk/core/patcher.py index bcdb59c1..8e4687e3 100644 --- a/aws_xray_sdk/core/patcher.py +++ b/aws_xray_sdk/core/patcher.py @@ -8,7 +8,7 @@ import wrapt from aws_xray_sdk import global_sdk_config -from .utils.compat import PY2, is_classmethod, is_instance_method +from .utils.compat import is_classmethod, is_instance_method log = logging.getLogger(__name__) @@ -55,17 +55,14 @@ def patch_all(double_patch=False): def _is_valid_import(module): module = module.replace('.', '/') - if PY2: - return bool(pkgutil.get_loader(module)) - else: - realpath = os.path.realpath(module) - is_module = os.path.isdir(realpath) and ( - os.path.isfile('{}/__init__.py'.format(module)) or os.path.isfile('{}/__init__.pyc'.format(module)) - ) - is_file = not is_module and ( - os.path.isfile('{}.py'.format(module)) or os.path.isfile('{}.pyc'.format(module)) - ) - return is_module or is_file + realpath = os.path.realpath(module) + is_module = os.path.isdir(realpath) and ( + os.path.isfile('{}/__init__.py'.format(module)) or os.path.isfile('{}/__init__.pyc'.format(module)) + ) + is_file = not is_module and ( + os.path.isfile('{}.py'.format(module)) or os.path.isfile('{}.pyc'.format(module)) + ) + return is_module or is_file def patch(modules_to_patch, raise_errors=True, ignore_module_patterns=None): diff --git a/aws_xray_sdk/core/plugins/ec2_plugin.py b/aws_xray_sdk/core/plugins/ec2_plugin.py index 5b8d3d2f..c749bbd4 100644 --- a/aws_xray_sdk/core/plugins/ec2_plugin.py +++ b/aws_xray_sdk/core/plugins/ec2_plugin.py @@ -1,13 +1,6 @@ import json import logging - -from aws_xray_sdk.core.utils.compat import PY2 - -if PY2: - from future.standard_library import install_aliases - install_aliases() - -from urllib.request import urlopen, Request +from urllib.request import Request, urlopen log = logging.getLogger(__name__) diff --git a/aws_xray_sdk/core/sampling/connector.py b/aws_xray_sdk/core/sampling/connector.py index 433d8405..a510a197 100644 --- a/aws_xray_sdk/core/sampling/connector.py +++ b/aws_xray_sdk/core/sampling/connector.py @@ -10,7 +10,6 @@ from .sampling_rule import SamplingRule from aws_xray_sdk.core.models.dummy_entities import DummySegment from aws_xray_sdk.core.context import Context -from aws_xray_sdk.core.utils.compat import PY2 class ServiceConnector: @@ -137,16 +136,8 @@ def _dt_to_epoch(self, dt): """ Convert a offset-aware datetime to POSIX time. """ - if PY2: - # The input datetime is from botocore unmarshalling and it is - # offset-aware so the timedelta of subtracting this time - # to 01/01/1970 using the same tzinfo gives us - # Unix Time (also known as POSIX Time). - time_delta = dt - datetime(1970, 1, 1).replace(tzinfo=dt.tzinfo) - return int(time_delta.total_seconds()) - else: - # Added in python 3.3+ and directly returns POSIX time. - return int(dt.timestamp()) + # Added in python 3.3+ and directly returns POSIX time. + return int(dt.timestamp()) def _is_rule_valid(self, record): # We currently only handle v1 sampling rules. diff --git a/aws_xray_sdk/core/utils/compat.py b/aws_xray_sdk/core/utils/compat.py index 88ec2998..a5f98d6b 100644 --- a/aws_xray_sdk/core/utils/compat.py +++ b/aws_xray_sdk/core/utils/compat.py @@ -1,16 +1,7 @@ import inspect -import sys - -PY2 = sys.version_info < (3,) -PY35 = sys.version_info >= (3, 5) - -if PY2: - annotation_value_types = (int, long, float, bool, str, unicode) # noqa: F821 - string_types = basestring # noqa: F821 -else: - annotation_value_types = (int, float, bool, str) - string_types = str +annotation_value_types = (int, float, bool, str) +string_types = str def is_classmethod(func): diff --git a/aws_xray_sdk/ext/httplib/patch.py b/aws_xray_sdk/ext/httplib/patch.py index bfb4fce2..91c5c24f 100644 --- a/aws_xray_sdk/ext/httplib/patch.py +++ b/aws_xray_sdk/ext/httplib/patch.py @@ -1,24 +1,17 @@ -from collections import namedtuple -import sys -import wrapt import fnmatch +from collections import namedtuple + import urllib3.connection +import wrapt from aws_xray_sdk.core import xray_recorder -from aws_xray_sdk.core.models import http from aws_xray_sdk.core.exceptions.exceptions import SegmentNotFoundException +from aws_xray_sdk.core.models import http from aws_xray_sdk.core.patcher import _PATCHED_MODULES -from aws_xray_sdk.ext.util import inject_trace_header, strip_url, unwrap, get_hostname - -if sys.version_info >= (3, 0, 0): - PY2 = False - httplib_client_module = 'http.client' - import http.client as httplib -else: - PY2 = True - httplib_client_module = 'httplib' - import httplib +from aws_xray_sdk.ext.util import get_hostname, inject_trace_header, strip_url, unwrap +httplib_client_module = 'http.client' +import http.client as httplib _XRAY_PROP = '_xray_prop' _XRay_Data = namedtuple('xray_data', ['method', 'host', 'url']) @@ -72,10 +65,6 @@ def http_response_processor(wrapped, instance, args, kwargs, return_value, def _xray_traced_http_getresponse(wrapped, instance, args, kwargs): - if not PY2 and kwargs.get('buffering', False): - # ignore py2 calls that fail as 'buffering` only exists in py2. - return wrapped(*args, **kwargs) - xray_data = getattr(instance, _XRAY_PROP, None) if not xray_data: return wrapped(*args, **kwargs) diff --git a/aws_xray_sdk/ext/sqlalchemy/util/decorators.py b/aws_xray_sdk/ext/sqlalchemy/util/decorators.py index fa67befc..8480788d 100644 --- a/aws_xray_sdk/ext/sqlalchemy/util/decorators.py +++ b/aws_xray_sdk/ext/sqlalchemy/util/decorators.py @@ -1,18 +1,12 @@ import re import types +from urllib.parse import urlparse, uses_netloc + +from sqlalchemy.engine.base import Connection from aws_xray_sdk.core import xray_recorder from aws_xray_sdk.ext.util import strip_url -from aws_xray_sdk.core.utils.compat import PY2 - -if PY2: - from future.standard_library import install_aliases - install_aliases() - -from urllib.parse import urlparse, uses_netloc -from sqlalchemy.engine.base import Connection - def decorate_all_functions(function_decorator): def decorator(cls): diff --git a/aws_xray_sdk/ext/sqlalchemy_core/patch.py b/aws_xray_sdk/ext/sqlalchemy_core/patch.py index acab1fd4..0551fe2b 100644 --- a/aws_xray_sdk/ext/sqlalchemy_core/patch.py +++ b/aws_xray_sdk/ext/sqlalchemy_core/patch.py @@ -1,20 +1,15 @@ import logging import sys - -if sys.version_info >= (3, 0, 0): - from urllib.parse import urlparse, uses_netloc -else: - from urlparse import urlparse, uses_netloc +from urllib.parse import urlparse, uses_netloc import wrapt +from sqlalchemy.sql.expression import ClauseElement from aws_xray_sdk.core import xray_recorder from aws_xray_sdk.core.patcher import _PATCHED_MODULES from aws_xray_sdk.core.utils import stacktrace from aws_xray_sdk.ext.util import unwrap -from sqlalchemy.sql.expression import ClauseElement - def _sql_meta(engine_instance, args): try: diff --git a/aws_xray_sdk/ext/util.py b/aws_xray_sdk/ext/util.py index ad9d5207..0c67e537 100644 --- a/aws_xray_sdk/ext/util.py +++ b/aws_xray_sdk/ext/util.py @@ -1,16 +1,10 @@ import re - -from aws_xray_sdk.core.models.trace_header import TraceHeader -from aws_xray_sdk.core.models import http +from urllib.parse import urlparse import wrapt -import sys - -if sys.version_info.major >= 3: # Python 3 and above - from urllib.parse import urlparse -else: # Python 2 and below - from urlparse import urlparse +from aws_xray_sdk.core.models import http +from aws_xray_sdk.core.models.trace_header import TraceHeader first_cap_re = re.compile('(.)([A-Z][a-z]+)') all_cap_re = re.compile('([a-z0-9])([A-Z])') diff --git a/tests/ext/aiohttp/test_middleware.py b/tests/ext/aiohttp/test_middleware.py index 9055cd55..84ecee75 100644 --- a/tests/ext/aiohttp/test_middleware.py +++ b/tests/ext/aiohttp/test_middleware.py @@ -5,22 +5,18 @@ """ import asyncio import sys -from aws_xray_sdk import global_sdk_config -try: - from unittest.mock import patch -except ImportError: - # NOTE: Python 2 dependency - from mock import patch +from unittest.mock import patch +import pytest from aiohttp import web from aiohttp.web_exceptions import HTTPUnauthorized -import pytest -from aws_xray_sdk.core.emitters.udp_emitter import UDPEmitter +from aws_xray_sdk import global_sdk_config from aws_xray_sdk.core.async_context import AsyncContext +from aws_xray_sdk.core.emitters.udp_emitter import UDPEmitter from aws_xray_sdk.core.models import http -from tests.util import get_new_stubbed_recorder from aws_xray_sdk.ext.aiohttp.middleware import middleware +from tests.util import get_new_stubbed_recorder class CustomStubbedEmitter(UDPEmitter): diff --git a/tests/ext/django/test_settings.py b/tests/ext/django/test_settings.py index 6c3c0f65..4867f90a 100644 --- a/tests/ext/django/test_settings.py +++ b/tests/ext/django/test_settings.py @@ -1,15 +1,11 @@ -try: - from unittest import mock -except ImportError: - # NOTE: Python 2 dependency - import mock +from unittest import mock import django -from aws_xray_sdk import global_sdk_config -from django.test import TestCase, override_settings -from django.conf import settings from django.apps import apps +from django.conf import settings +from django.test import TestCase, override_settings +from aws_xray_sdk import global_sdk_config from aws_xray_sdk.core import xray_recorder from aws_xray_sdk.core.sampling.sampler import LocalSampler diff --git a/tests/ext/httplib/test_httplib.py b/tests/ext/httplib/test_httplib.py index 5ddf9573..09aea4e2 100644 --- a/tests/ext/httplib/test_httplib.py +++ b/tests/ext/httplib/test_httplib.py @@ -1,18 +1,11 @@ +import http.client as httplib +from urllib.parse import urlparse + import pytest -import sys -from aws_xray_sdk.core import patch -from aws_xray_sdk.core import xray_recorder +from aws_xray_sdk.core import patch, xray_recorder from aws_xray_sdk.core.context import Context -from aws_xray_sdk.ext.util import strip_url, get_hostname - -if sys.version_info >= (3, 0, 0): - import http.client as httplib - from urllib.parse import urlparse -else: - import httplib - from urlparse import urlparse - +from aws_xray_sdk.ext.util import get_hostname, strip_url # httpbin.org is created by the same author of requests to make testing http easy. BASE_URL = 'httpbin.org' @@ -25,7 +18,7 @@ def construct_ctx(): so that later subsegment can be attached. After each test run it cleans up context storage again. """ - from aws_xray_sdk.ext.httplib import unpatch, reset_ignored + from aws_xray_sdk.ext.httplib import reset_ignored, unpatch patch(('httplib',)) xray_recorder.configure(service='test', sampling=False, context=Context()) diff --git a/tests/test_plugins.py b/tests/test_plugins.py index 9b6a2aab..4309780a 100644 --- a/tests/test_plugins.py +++ b/tests/test_plugins.py @@ -1,9 +1,6 @@ +from unittest.mock import patch + from aws_xray_sdk.core.plugins.utils import get_plugin_modules -try: - from unittest.mock import patch -except ImportError: - # NOTE: Python 2 dependency - from mock import patch supported_plugins = ( 'ec2_plugin', diff --git a/tests/test_trace_entities.py b/tests/test_trace_entities.py index 7d987ed0..421e9a5b 100644 --- a/tests/test_trace_entities.py +++ b/tests/test_trace_entities.py @@ -1,7 +1,6 @@ # -*- coding: iso-8859-15 -*- import pytest -import sys from aws_xray_sdk.core.models.segment import Segment from aws_xray_sdk.core.models.subsegment import Subsegment @@ -233,10 +232,7 @@ def test_add_exception_referencing(): subseg_cause = subseg.cause assert isinstance(subseg_cause, dict) - if sys.version_info.major == 2: - assert isinstance(seg_cause, basestring) - else: - assert isinstance(seg_cause, str) + assert isinstance(seg_cause, str) assert seg_cause == subseg_cause['exceptions'][0].id @@ -270,7 +266,7 @@ def test_add_exception_appending_exceptions(): def test_adding_subsegments_with_recorder(): xray_recorder.configure(sampling=False) xray_recorder.clear_trace_entities() - + segment = xray_recorder.begin_segment('parent'); subsegment = xray_recorder.begin_subsegment('sampled-child') unsampled_subsegment = xray_recorder.begin_subsegment_without_sampling('unsampled-child1') @@ -281,4 +277,4 @@ def test_adding_subsegments_with_recorder(): assert unsampled_subsegment.sampled == False assert unsampled_child_subsegment.sampled == False - xray_recorder.clear_trace_entities() \ No newline at end of file + xray_recorder.clear_trace_entities() diff --git a/tests/util.py b/tests/util.py index 2510b0b7..d5f51d12 100644 --- a/tests/util.py +++ b/tests/util.py @@ -4,7 +4,6 @@ from aws_xray_sdk.core.recorder import AWSXRayRecorder from aws_xray_sdk.core.emitters.udp_emitter import UDPEmitter from aws_xray_sdk.core.sampling.sampler import DefaultSampler -from aws_xray_sdk.core.utils.compat import PY35 class StubbedEmitter(UDPEmitter): @@ -36,12 +35,9 @@ def get_new_stubbed_recorder(): """ Returns a new AWSXRayRecorder object with emitter stubbed """ - if not PY35: - recorder = AWSXRayRecorder() - else: - from aws_xray_sdk.core.async_recorder import AsyncAWSXRayRecorder - recorder = AsyncAWSXRayRecorder() + from aws_xray_sdk.core.async_recorder import AsyncAWSXRayRecorder + recorder = AsyncAWSXRayRecorder() recorder.configure(emitter=StubbedEmitter(), sampler=StubbedSampler()) return recorder @@ -85,7 +81,7 @@ def find_subsegment_by_annotation(segment, key, value): result = _search_entity_by_annotation(entity, key, value) if result is not None: return result - return None + return None def _search_entity_by_annotation(entity, key, value): @@ -102,4 +98,4 @@ def _search_entity_by_annotation(entity, key, value): result = _search_entity_by_annotation(s, key, value) if result is not None: return result - return None \ No newline at end of file + return None From 3504998052c5ffdd5ba271ff4eb0af3264392809 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20K=C3=A4ufl?= Date: Tue, 4 Apr 2023 11:10:44 +0200 Subject: [PATCH 7/8] Remove unnecessary future imports --- aws_xray_sdk/ext/boto_utils.py | 2 -- tests/ext/flask_sqlalchemy/test_query.py | 1 - tests/ext/sqlalchemy/test_query.py | 1 - tests/ext/sqlalchemy_core/test_base.py | 2 -- 4 files changed, 6 deletions(-) diff --git a/aws_xray_sdk/ext/boto_utils.py b/aws_xray_sdk/ext/boto_utils.py index cb65c854..9f7f41a6 100644 --- a/aws_xray_sdk/ext/boto_utils.py +++ b/aws_xray_sdk/ext/boto_utils.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import -# Need absolute import as botocore is also in the current folder for py27 import json import pkgutil diff --git a/tests/ext/flask_sqlalchemy/test_query.py b/tests/ext/flask_sqlalchemy/test_query.py index 69f0bd7a..b2732b8f 100644 --- a/tests/ext/flask_sqlalchemy/test_query.py +++ b/tests/ext/flask_sqlalchemy/test_query.py @@ -1,4 +1,3 @@ -from __future__ import absolute_import import pytest from aws_xray_sdk.core import xray_recorder from aws_xray_sdk.core.context import Context diff --git a/tests/ext/sqlalchemy/test_query.py b/tests/ext/sqlalchemy/test_query.py index c664b724..621e5b54 100644 --- a/tests/ext/sqlalchemy/test_query.py +++ b/tests/ext/sqlalchemy/test_query.py @@ -1,4 +1,3 @@ -from __future__ import absolute_import import pytest from aws_xray_sdk.core import xray_recorder from aws_xray_sdk.core.context import Context diff --git a/tests/ext/sqlalchemy_core/test_base.py b/tests/ext/sqlalchemy_core/test_base.py index 74bbe976..f187ae4f 100644 --- a/tests/ext/sqlalchemy_core/test_base.py +++ b/tests/ext/sqlalchemy_core/test_base.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import - import pytest from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.ext.declarative import declarative_base From 649919986d06f5aafcb36fa6defc4f51585d3c59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20K=C3=A4ufl?= Date: Tue, 4 Apr 2023 11:15:38 +0200 Subject: [PATCH 8/8] Remove `string_types` from compat module --- aws_xray_sdk/core/models/entity.py | 10 +++++----- aws_xray_sdk/core/models/throwable.py | 4 +--- aws_xray_sdk/core/recorder.py | 7 +++---- aws_xray_sdk/core/utils/compat.py | 1 - 4 files changed, 9 insertions(+), 13 deletions(-) diff --git a/aws_xray_sdk/core/models/entity.py b/aws_xray_sdk/core/models/entity.py index 12663b1d..a2150a5e 100644 --- a/aws_xray_sdk/core/models/entity.py +++ b/aws_xray_sdk/core/models/entity.py @@ -6,7 +6,7 @@ import json -from ..utils.compat import annotation_value_types, string_types +from ..utils.compat import annotation_value_types from ..utils.conversion import metadata_to_dict from .throwable import Throwable from . import http @@ -113,7 +113,7 @@ def put_http_meta(self, key, value): return if key == http.STATUS: - if isinstance(value, string_types): + if isinstance(value, str): value = int(value) self.apply_status_code(value) @@ -139,7 +139,7 @@ def put_annotation(self, key, value): """ self._check_ended() - if not isinstance(key, string_types): + if not isinstance(key, str): log.warning("ignoring non string type annotation key with type %s.", type(key)) return @@ -165,7 +165,7 @@ def put_metadata(self, key, value, namespace='default'): """ self._check_ended() - if not isinstance(namespace, string_types): + if not isinstance(namespace, str): log.warning("ignoring non string type metadata namespace") return @@ -271,7 +271,7 @@ def serialize(self): def to_dict(self): """ Convert Entity(Segment/Subsegment) object to dict - with required properties that have non-empty values. + with required properties that have non-empty values. """ entity_dict = {} diff --git a/aws_xray_sdk/core/models/throwable.py b/aws_xray_sdk/core/models/throwable.py index 4d92942a..21d6483f 100644 --- a/aws_xray_sdk/core/models/throwable.py +++ b/aws_xray_sdk/core/models/throwable.py @@ -3,8 +3,6 @@ import binascii import logging -from ..utils.compat import string_types - log = logging.getLogger(__name__) @@ -31,7 +29,7 @@ def __init__(self, exception, stack, remote=False): message = None # do not record non-string exception message - if isinstance(message, string_types): + if isinstance(message, str): self.message = message self.type = type(exception).__name__ diff --git a/aws_xray_sdk/core/recorder.py b/aws_xray_sdk/core/recorder.py index 09cba247..debc1604 100644 --- a/aws_xray_sdk/core/recorder.py +++ b/aws_xray_sdk/core/recorder.py @@ -18,7 +18,6 @@ from .plugins.utils import get_plugin_modules from .lambda_launcher import check_in_lambda from .exceptions.exceptions import SegmentNameMissingException, SegmentNotFoundException -from .utils.compat import string_types from .utils import stacktrace log = logging.getLogger(__name__) @@ -288,7 +287,7 @@ def _begin_subsegment_helper(self, name, namespace='local', beginWithoutSampling if not segment: log.warning("No segment found, cannot begin subsegment %s." % name) return None - + current_entity = self.get_trace_entity() if not current_entity.sampled or beginWithoutSampling: subsegment = DummySubsegment(segment, name) @@ -486,7 +485,7 @@ def _populate_runtime_context(self, segment, sampling_decision): segment.set_aws(copy.deepcopy(self._aws_metadata)) segment.set_service(SERVICE_INFO) - if isinstance(sampling_decision, string_types): + if isinstance(sampling_decision, str): segment.set_rule_name(sampling_decision) def _send_segment(self): @@ -562,7 +561,7 @@ def dynamic_naming(self): @dynamic_naming.setter def dynamic_naming(self, value): - if isinstance(value, string_types): + if isinstance(value, str): self._dynamic_naming = DefaultDynamicNaming(value, self.service) else: self._dynamic_naming = value diff --git a/aws_xray_sdk/core/utils/compat.py b/aws_xray_sdk/core/utils/compat.py index a5f98d6b..00fbb352 100644 --- a/aws_xray_sdk/core/utils/compat.py +++ b/aws_xray_sdk/core/utils/compat.py @@ -1,7 +1,6 @@ import inspect annotation_value_types = (int, float, bool, str) -string_types = str def is_classmethod(func):