from flask import Flask, jsonify, json, Response, request from flask_cors import CORS import mysfitsTableClient import requests import json import os import logging from aws_xray_sdk.core import xray_recorder from aws_xray_sdk.core import patch from aws_xray_sdk.ext.flask.middleware import XRayMiddleware # logging if 'LOGLEVEL' in os.environ: loglevel = os.environ['LOGLEVEL'].upper() else: loglevel = 'ERROR' logging.basicConfig(level=loglevel) plugins = ('ecs_plugin',) xray_recorder.configure( service = 'Mysfits Service', plugins = plugins, #daemon_address='172.17.0.2:2000', # for local testing context_missing='LOG_ERROR' ) libraries = ('boto3',) patch(libraries) app = Flask(__name__) CORS(app) app.logger XRayMiddleware(app, xray_recorder) if (os.environ['AWS_REGION'] != ''): region = os.environ['AWS_REGION'] else: r = requests.get("http://169.254.169.254/latest/dynamic/instance-identity/document") region = r.json()['region'] # A very basic API created using Flask that has two possible routes for requests. # The service basepath has a short response just to ensure that healthchecks # sent to the service root will receive a healthy response. @app.route("/") def mainSite(): http_response = ''' Mythical Mysfits
Current region: %s


{{mysfit.name}}
{{mysfit.Name}}


Species: {{mysfit.species}}
Age: {{mysfit.age}}
Good/Evil: {{mysfit.goodevil}}
Lawful/Chaotic: {{mysfit.lawchaos}}



  This site was created for use in the AWS Modern Application Workshop. Please see details here.

''' % region return http_response # Returns the data for all of the Mysfits to be displayed on # the website. If no filter query string is provided, all mysfits are retrived # and returned. If a querystring filter is provided, only those mysfits are queried. @app.route("/mysfits") def getMysfits(): filterCategory = request.args.get('filter') if filterCategory: filterValue = request.args.get('value') queryParam = { 'filter': filterCategory, 'value': filterValue } # a filter query string was found, query only for those mysfits. serviceResponse = mysfitsTableClient.queryMysfits(queryParam) else: # no filter was found, retrieve all mysfits. app.logger.info('retrieving all mysfits') serviceResponse = mysfitsTableClient.getAllMysfits() flaskResponse = Response(serviceResponse) flaskResponse.headers["Content-Type"] = "application/json" return flaskResponse # Run the service on the local server it has been deployed to, # listening on port 8080. if __name__ == "__main__": app.run(host="0.0.0.0", port=8080)