diff --git a/contrib/opencensus-ext-flask/opencensus/ext/flask/flask_middleware.py b/contrib/opencensus-ext-flask/opencensus/ext/flask/flask_middleware.py index ebd8d24ff..fcbdc41e7 100644 --- a/contrib/opencensus-ext-flask/opencensus/ext/flask/flask_middleware.py +++ b/contrib/opencensus-ext-flask/opencensus/ext/flask/flask_middleware.py @@ -176,9 +176,11 @@ def _after_request(self, response): try: tracer = execution_context.get_opencensus_tracer() - tracer.add_attribute_to_current_span( - HTTP_ROUTE, flask.request.url_rule.rule - ) + url_rule = flask.request.url_rule + if url_rule is not None: + tracer.add_attribute_to_current_span( + HTTP_ROUTE, url_rule.rule + ) tracer.add_attribute_to_current_span( HTTP_STATUS_CODE, response.status_code diff --git a/contrib/opencensus-ext-flask/tests/test_flask_middleware.py b/contrib/opencensus-ext-flask/tests/test_flask_middleware.py index 6cb59f177..bcd11a506 100644 --- a/contrib/opencensus-ext-flask/tests/test_flask_middleware.py +++ b/contrib/opencensus-ext-flask/tests/test_flask_middleware.py @@ -19,6 +19,7 @@ from google.rpc import code_pb2 import flask +from werkzeug.exceptions import NotFound import mock from opencensus.ext.flask import flask_middleware @@ -311,6 +312,48 @@ def test__after_request_sampled(self): self.assertEqual(span.attributes, expected_attributes) assert isinstance(span.parent_span, base.NullContextManager) + def test__after_request_invalid_url(self): + flask_trace_header = 'traceparent' + trace_id = '2dd43a1d6b2549c6bc2a1a54c2fc0b05' + span_id = '6e0c63257de34c92' + flask_trace_id = '00-{}-{}-00'.format(trace_id, span_id) + + app = self.create_app() + flask_middleware.FlaskMiddleware( + app=app, + sampler=samplers.AlwaysOnSampler() + ) + + context = app.test_request_context( + path='/this-url-does-not-exist', + headers={flask_trace_header: flask_trace_id} + ) + + with context: + app.preprocess_request() + tracer = execution_context.get_opencensus_tracer() + self.assertIsNotNone(tracer) + + span = tracer.current_span() + + try: + rv = app.dispatch_request() + except NotFound as e: + rv = app.handle_user_exception(e) + app.finalize_request(rv) + + # http.route should not be set + expected_attributes = { + 'http.host': u'localhost', + 'http.method': u'GET', + 'http.path': u'/this-url-does-not-exist', + 'http.url': u'http://localhost/this-url-does-not-exist', + 'http.status_code': 404 + } + + self.assertEqual(span.attributes, expected_attributes) + assert isinstance(span.parent_span, base.NullContextManager) + def test__after_request_blacklist(self): flask_trace_header = 'traceparent' trace_id = '2dd43a1d6b2549c6bc2a1a54c2fc0b05'