def get_chalice_app(flask_app): app = chalice.Chalice(app_name=flask_app.name) flask_app.debug = True app.debug = flask_app.debug app.log.setLevel(logging.DEBUG) def dispatch(*args, **kwargs): uri_params = app.current_request.uri_params or {} path = app.current_request.context["resourcePath"].format(**uri_params) req_body = app.current_request.raw_body if app.current_request._body is not None else None with flask_app.test_request_context(path=path, base_url="https://{}".format(app.current_request.headers["host"]), query_string=app.current_request.query_params, method=app.current_request.method, headers=list(app.current_request.headers.items()), data=req_body, environ_base=app.current_request.stage_vars): flask_res = flask_app.full_dispatch_request() res_headers = dict(flask_res.headers) # API Gateway/Cloudfront adds a duplicate Content-Length with a different value (not sure why) res_headers.pop("Content-Length", None) return chalice.Response(status_code=flask_res._status_code, headers=res_headers, body="".join([c.decode() if isinstance(c, bytes) else c for c in flask_res.response])) routes = collections.defaultdict(list) for rule in flask_app.url_map.iter_rules(): routes[re.sub(r"<(.+?)(:.+?)?>", r"{\1}", rule.rule).rstrip("/")] += rule.methods for route, methods in routes.items(): app.route(route, methods=list(set(methods) - {"OPTIONS"}), cors=True)(dispatch) with open(os.path.join(pkg_root, "index.html")) as fh: swagger_ui_html = fh.read() @app.route("/") def serve_swagger_ui(): return chalice.Response(status_code=200, headers={"Content-Type": "text/html"}, body=swagger_ui_html) return app
""" lopper/app ~~~~~~~~~~ Contains `chalice` app for running an AWS Lambda function responsible for receiving GitHub webhook requests. """ import chalice import typing from chalicelib import auth, conf, hub, payload, response app = chalice.Chalice(app_name=conf.APPLICATION_NAME, debug=conf.DEBUG_MODE) @app.route('/lopper', methods=['POST']) def handler(): # Validate the loaded configuration. resp = is_configuration_valid(conf) if not resp: return resp # Authorize the request by validating it's signature against our shared secret token. resp = is_request_authentic(app.current_request) if not resp: return resp # Example the request payload to determine if it's an event we should process. resp = is_request_acceptable(app.current_request) if not resp: return resp
import chalice app = chalice.Chalice(app_name="{{cookiecutter.project}}") @app.route("/") def index(): """This is just an initial test endpoint.""" # TODO: delete this method once finished testing return {"hello": "{{cookiecutter.project}}"}
Shows how to implement a REST API using AWS Chalice. This REST API stores and retrieves fictional data representing COVID-19 cases in the United States. You can find actual COVID-19 data in Amazon's public data lake. * https://aws.amazon.com/covid-19-data-lake/ """ import datetime import decimal import json import logging import urllib.parse import chalice import chalicelib.covid_data app = chalice.Chalice(app_name='fictional-covid') app.debug = True # Set this to False for production use. logger = logging.getLogger() logger.setLevel(logging.INFO) storage = chalicelib.covid_data.Storage.from_env() def convert_decimal_to_int(obj): """ Amazon DynamoDB returns numbers in Python Decimal format, which are converted to float by the JSON serializer. This function instead converts them to int. Pass this function to the `json.dumps` function for custom conversion. :param obj: The current object being deserialized.
import datetime from decimal import Decimal import boto3 import chalice from boto3.dynamodb.conditions import Key from chalice import NotFoundError TABLE_NAME = 'temperatures' app = chalice.Chalice(app_name="SaunaThermometer") dynamodb = boto3.resource('dynamodb', region_name='eu-north-1') table = dynamodb.Table(TABLE_NAME) @app.route("/", methods=["POST"]) def post_temperature(): data = app.current_request.json_body data['temperature'] = Decimal(data['temperature']) table.put_item(Item=data) return chalice.Response(body='', status_code=204) @app.route("/register/{sensor_id}") def register(sensor_id): ret = dynamodb.meta.client.update_item( TableName=TABLE_NAME, Key={ "sensor_id": "sensors", "timestamp": 0
import datetime import json from marshmallow import ValidationError from example import models, settings, events import chalice from typing import Callable, Optional, List from chalice import Response from example.exceptions import UpException app = chalice.Chalice(app_name=settings.APP_NAME) app.debug = settings.DEBUG headers = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "POST,GET,OPTIONS", "Access-Control-Max-Age": "600" } def validate_route(input_schema: Optional[Callable] = None) -> Callable: """Decorator to handle exceptions and optionally validate input marshmallow.Schema""" def decorator_fn(route_fn: Callable) -> Callable: def decorator() -> Response: try: if input_schema is not None: try: return route_fn(input_schema().load( app.current_request.json_body))
def get_chalice_app(flask_app): app = chalice.Chalice(app_name=flask_app.name) flask_app.debug = True app.debug = flask_app.debug app.log.setLevel(logging.DEBUG) def dispatch(*args, **kwargs): uri_params = app.current_request.uri_params or {} path = app.current_request.context["resourcePath"].format(**uri_params) req_body = app.current_request.raw_body if app.current_request._body is not None else None with flask_app.test_request_context( path=path, base_url="https://{}".format( app.current_request.headers["host"]), query_string=app.current_request.query_params, method=app.current_request.method, headers=list(app.current_request.headers.items()), data=req_body, environ_base=app.current_request.stage_vars): flask_res = flask_app.full_dispatch_request() res_headers = dict(flask_res.headers) # API Gateway/Cloudfront adds a duplicate Content-Length with a different value (not sure why) res_headers.pop("Content-Length", None) return chalice.Response(status_code=flask_res._status_code, headers=res_headers, body="".join([ c.decode() if isinstance(c, bytes) else c for c in flask_res.response ])) routes = collections.defaultdict(list) for rule in flask_app.url_map.iter_rules(): routes[re.sub(r"<(.+?)(:.+?)?>", r"{\1}", rule.rule).rstrip("/")] += rule.methods for route, methods in routes.items(): app.route(route, methods=list(set(methods) - {"OPTIONS"}), cors=True)(dispatch) with open(os.path.join(pkg_root, "index.html")) as fh: swagger_ui_html = fh.read() @app.route("/") def serve_swagger_ui(): return chalice.Response(status_code=200, headers={"Content-Type": "text/html"}, body=swagger_ui_html) @app.route("/version") def version(): data = {'version_info': {'version': os.getenv('MATRIX_VERSION')}} return chalice.Response(status_code=200, headers={'Content-Type': "application/json"}, body=data) @app.route("/internal/health") def health(): # Level 2 healthcheck: Test connection can be made to redshift cluster but do not run any queries redshift_handler.transaction([]) # Level 2 healthcheck checks that ecs query runner is active with expected number of tasks service_name = f"matrix-service-query-runner-{os.environ['DEPLOYMENT_STAGE']}" service = ecs_client.describe_services(cluster=service_name, services=[service_name ])["services"][0] status = service["status"] running_task_count = service["runningCount"] assert status == 'ACTIVE' assert running_task_count > 0 return chalice.Response(status_code=200, headers={'Content-Type': "text/html"}, body="OK") @app.route("/dss/notification", methods=['POST']) def dss_notification(): body = app.current_request.json_body bundle_uuid = body['match']['bundle_uuid'] bundle_version = body['match']['bundle_version'] subscription_id = body['subscription_id'] event_type = body['event_type'] config = MatrixInfraConfig() hmac_secret_key = config.dss_subscription_hmac_secret_key.encode() HTTPSignatureAuth.verify( requests.Request(url="http://host/dss/notification", method=app.current_request.method, headers=app.current_request.headers), key_resolver=lambda key_id, algorithm: hmac_secret_key) payload = { 'bundle_uuid': bundle_uuid, 'bundle_version': bundle_version, 'event_type': event_type, } queue_url = config.notification_q_url SQSHandler().add_message_to_queue(queue_url, payload) return chalice.Response( status_code=requests.codes.ok, body=f"Received notification from subscription {subscription_id}: " f"{event_type} {bundle_uuid}.{bundle_version}") return app
import boto3 import chalice app = chalice.Chalice(app_name='students_service') def get_db(): """Get DB object""" import queries dynamodb = boto3.resource('dynamodb') return queries.DatabaseOperations(dynamodb.Table('students')) @app.route('/') def index(): """Root view""" return {'details': 'This are API endpoints for students.'} @app.route('/all-students', methods=['GET']) def all_students(): """Get all students data at a time.""" return {'students': get_db().get_all_items()} @app.route('/student', methods=['GET', 'POST', 'PUT', 'DELETE']) def student(): """Perform operations on individual student Base Schema: { "s_id": number,
import chalice import boto3 import botocore import chalicelib.constants import chalicelib.ca2Questions import chalicelib.ca220Questions import chalicelib.questions import chalicelib.cdaQuestions import chalicelib.cdanQuestions from boto3.dynamodb.conditions import Key, Attr import json #from urllib import unquote from urllib.parse import unquote app = chalice.Chalice(app_name='awsCert') dynamodb = boto3.resource('dynamodb', region_name='us-west-2') ca2_table = dynamodb.Table(chalicelib.constants.CA2QUESTIONS_TABLE_NAME) ca220_table = dynamodb.Table(chalicelib.constants.CA220QUESTIONS_TABLE_NAME) c2p_table = dynamodb.Table(chalicelib.constants.C2PQUESTIONS_TABLE_NAME) cda_table = dynamodb.Table(chalicelib.constants.CDAQUESTIONS_TABLE_NAME) cml_table = dynamodb.Table(chalicelib.constants.CMLQUESTIONS_TABLE_NAME) cdan_table = dynamodb.Table(chalicelib.constants.CDANQUESTIONS_TABLE_NAME) @app.route('/', cors=True) def index(): return {'hello': 'AWS Cert world'} @app.route('/email/{email}/password/{password}', cors=True)
import boto3 import chalice app = chalice.Chalice(app_name='teachers_service') def get_db(): """Get DB object""" import queries dynamodb = boto3.resource('dynamodb') return queries.DatabaseOperations(dynamodb.Table('teachers')) @app.route('/') def index(): """Root view""" return {'details': 'This are API endpoints for teachers.'} @app.route('/all-teachers', methods=['GET']) def all_teachers(): """Get all teachers data at a time.""" return {'teachers': get_db().get_all_items()} @app.route('/teacher', methods=['GET', 'POST', 'PUT', 'DELETE']) def teacher(): """Perform operations on individual teacher Base Schema: { "t_id": number,
import chalice import chalicelib.questions import chalicelib.users import chalicelib.constants app = chalice.Chalice(app_name='chalice-trivia') cognito_authorizer = chalice.CognitoUserPoolAuthorizer( 'MyCognitoAuthorizer', provider_arns=[chalicelib.constants.POOL_ARN]) @app.route('/questions/{question_id}', cors=True) def get_question(question_id): table = chalicelib.questions.QuestionsTable() question = table.get_question(question_id) if not question: raise chalice.NotFoundError('Requested resource does not exist') return { 'question_id': question.question_id, 'question': question.question, 'possible_answers': question.possible_answers } @app.route('/questions/{question_id}', methods=['POST'], cors=True) def answer_question(question_id): if 'answer' not in app.current_request.json_body: raise chalice.BadRequestError('Missing "answer" in request body') provided_answer = app.current_request.json_body['answer'] table = chalicelib.questions.QuestionsTable() question = table.get_question(question_id)
"Staking", "Spending", "Reserved", "Test", "User-generated" ) DEFAULT_START_TIME = 0 def _is_debug(debug=None): return debug and debug.strip().lower() in ( "true", "yes", "on", "1", ) app = chalice.Chalice( app_name="chalice-api", debug=_is_debug(debug=os.environ.get("DEBUG")), ) # Helper functions def _select(q, args=None, one=False): conn_str = "postgresql://%s:%s@%s:%s/%s" % ( os.environ["DB_USERNAME"], os.environ["DB_PASSWORD"], os.environ["DB_HOST"], os.environ["DB_PORT"], os.environ["DB_NAME"], ) with psycopg2.connect(conn_str) as conn: with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as c: c.execute(q, args or {})
voice: name of the voice to use """ import contextlib import tempfile import wave import boto3 import chalice DEFAULT_SAMPLE_RATE = 8000 DEFAULT_VOICE = 'Matthew' MAX_TEXT_BYTES = 20480 app = chalice.Chalice(app_name='squawk') app.debug = False POLLY = boto3.client('polly') @app.route('/') def show_help(): app.log.debug('show_help') return chalice.Response( body=__doc__.format(stage=app.current_request.context['stage']), headers={'Content-Type': 'text/plain'}, status_code=200) @app.route('/voices') def get_voices():
import chalice import chalicelib.questions import chalicelib.users import chalicelib.constants app = chalice.Chalice(app_name='triviaApp') cognito_authorizer = chalice.CognitoUserPoolAuthorizer( 'MyCognitoAuthorizer', provider_arns=[chalicelib.constants.POOL_ARN]) @app.route('/questions/{question_id}', cors=True) def get_question(question_id): table = chalicelib.questions.QuestionsTable() question = table.get_question(question_id) if not question: raise chalice.NotFoundError('Requested resource does not exist') return { 'question_id': question.question_id, 'question': question.question, 'possible_answers': question.possible_answers } @app.route('/questions/{question_id}', methods=['POST'], cors=True) def answer_question(question_id): if 'answer' not in app.current_request.json_body: raise chalice.BadRequestError('Missing "answer" in request body') provided_answer = app.current_request.json_body['answer'] table = chalicelib.questions.QuestionsTable() question = table.get_question(question_id)