Skip to content

Instantly share code, notes, and snippets.

@defanator
Created March 22, 2021 14:36
Show Gist options
  • Save defanator/c38da041617691033aea0d94f5f7423b to your computer and use it in GitHub Desktop.
Save defanator/c38da041617691033aea0d94f5f7423b to your computer and use it in GitHub Desktop.
Sample app demonstrating nginx + opentracing with Flask
#!/usr/bin/env python3
import hashlib
import logging
from jaeger_client import Config
from flask_opentracing import FlaskTracing
from flask import Flask, request
from werkzeug.debug import get_current_traceback
from random import randint
upload_app = Flask(__name__)
@upload_app.route("/", methods=['GET', 'POST'])
def default():
try:
environ_summary = "ENVIRON:\n\n" + "\n".join(["{0}: {1}".format(k, request.environ[k]) for k in sorted(request.environ.keys())]) + "\n"
args = "REQUEST ARGS: %s" % request.args
body = "REQUETS BODY: %s" % request.data
return "%s\n%s\n%s\n" % (args, body, environ_summary)
except Exception as e:
track = get_current_traceback(skip=1, show_hidden_frames=True, ignore_system_exceptions=False)
track.log()
abort(500)
@upload_app.route("/upload/", methods=['GET', 'POST'])
@upload_app.route("/upload-http/", methods=['GET', 'POST'])
def upload():
logging.info("Request headers:\n%s" % request.headers)
with jaeger_tracer.start_active_span('ProcessUpload') as scope:
scope.span.log_kv({'ProcessUpload': 'started'})
scope.span.set_tag('payload-size', int(request.headers.get('Content-Length')) if 'Content-Length' in request.headers else 0)
response_body = ''
if 'Content-Length' in request.headers and int(request.headers.get('Content-Length')):
body = request.stream.read()
for x in range(1, randint(2, 10)):
with jaeger_tracer.start_active_span('SubPart%02d' % x) as sub_scope:
sub_scope.span.log_kv({'subpart_iteration': x, 'action': 'begin'})
m = hashlib.md5()
m.update(body)
response_body = response_body + "%d:%d:%s\n" % (x, len(body), m.hexdigest())
sub_scope.span.log_kv({'subpart_iteration': x, 'action': 'end'})
logging.info('ProcessUpload finished with %d iterations' % x)
else:
response_body = 'no data was uploaded'
try:
scope.span.set_tag('iterations', x)
except NameError:
pass
scope.span.log_kv({'ProcessUpload': 'finished'})
return response_body
@upload_app.errorhandler(500)
def internal_error(error):
return "500 error"
if __name__ == "__main__":
log_level = logging.DEBUG
logging.getLogger('').handlers = []
logging.basicConfig(format='%(asctime)s %(message)s', level=log_level)
config = Config(config={}, service_name='upload-app', validate=True)
jaeger_tracer = config.initialize_tracer()
tracing = FlaskTracing(jaeger_tracer, app=upload_app)
upload_app.debug = True
upload_app.config['PROPAGATE_EXCEPTIONS'] = True
upload_app.run(host='127.0.0.1', port=8080)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment