Skip to content

Instantly share code, notes, and snippets.

@homingli
Created December 18, 2017 22:39
Show Gist options
  • Save homingli/488054933ecd0487ae5306ad91390a0d to your computer and use it in GitHub Desktop.
Save homingli/488054933ecd0487ae5306ad91390a0d to your computer and use it in GitHub Desktop.
Example Flask Container with X-Ray
FROM python:3-alpine
RUN pip3 install boto3 flask aws_xray_sdk
COPY app.py /
ENTRYPOINT [ "python", "/app.py" ]
EXPOSE 5000
from flask import Flask, jsonify
from timeit import default_timer as timer
import boto3,sys,os,botocore.config
from aws_xray_sdk.core import xray_recorder, patch_all
from aws_xray_sdk.ext.flask.middleware import XRayMiddleware
patch_all() # xray applied to supported libraries
app = Flask(__name__)
config = botocore.config.Config(connect_timeout=1, read_timeout=1, retries={'max_attempts':0})
s3 = boto3.client('s3',config=config)
XRAY_HOST=os.getenv('XRAY_SERVICE_HOST', '127.0.0.1')
XRAY_PORT=os.getenv('XRAY_SERVICE_PORT', str(2000))
HOSTNAME=os.getenv('HOSTNAME', 'localhost')
xray_recorder.configure(service='Demo App',sampling=False)
xray_recorder.configure(plugins=['EC2Plugin','ECSPlugin'])
xray_recorder.configure(daemon_address=XRAY_HOST+':'+XRAY_PORT)
XRayMiddleware(app, xray_recorder)
@app.route('/')
def helloworld():
return 'hello world'
@app.route('/s3')
def heads3obj():
s3bucket='<YourBucket>'
s3key='<YourKey>'
document = xray_recorder.current_segment()
document.put_annotation("s3resource",'/'.join((s3bucket,s3key)))
start = timer()
try:
s3.head_object(Bucket=s3bucket,Key=s3key)
except:
etype, emsg, etrace = sys.exc_info()
response = jsonify({'result':'fail','took':-999,'hostname':HOSTNAME,'reason':str(emsg)})
response.headers.add('Access-Control-Allow-Origin', '*')
response.status_code=503 # Service Unavailable
return response
end = timer()
# time diff * 1000 to convert to ms
response = jsonify({'result':'success','took':round((end - start)*1000,5),'hostname':HOSTNAME})
response.headers.add('Access-Control-Allow-Origin', '*')
return response
if __name__ == '__main__':
app.run(debug=True,host='0.0.0.0')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment