from chalice import Chalice import boto3 app = Chalice(app_name='{{cookiecutter.component_id}}') {% if cookiecutter.debug_mode == "y" %} app.debug = True {% else %} app.debug = False {% endif %} @app.route('/') def index(): return {'message': '{{cookiecutter.message}}'} @app.route('/default') def index(): return {'default_message': '{{cookiecutter.default_message}}'}
from chalice import Chalice #AWS library for packaging, deploying and managing severless APIs import psycopg2 #used to connect to a PSQL database and run queries from decimal import Decimal from datetime import datetime app = Chalice(app_name='locale-api') app.debug = True ##allow function error messages, if any to be sent as response. def create_conn( ): #function to try to esatblish a connection the database, return the connection object conn = None try: conn = psycopg2.connect( dbname='XRides', user='******', password='******', host='locale-ai.cbx79mt5d5sd.ap-south-1.rds.amazonaws.com', port='5432') except: print('cannot connect') return conn @app.route('/', methods=['POST']) # POST method endpoint def index(): req_data = app.current_request.to_dict() #stores the http request data query_params = req_data[ 'query_params'] # stores all the data passed through querry parameters
from chalice import Chalice, BadRequestError, NotFoundError import urlparse import json import boto3 from botocore.exceptions import ClientError app = Chalice(app_name='hellochalice') app.debug = True CITIES_TO_STATE = { 'seattle': 'WA', 'portland': 'OR', } OBJECTS = {} S3 = boto3.client('s3', region_name='us-west-2') BUCKET = 'chalice-tutorial-s3-bucket' @app.route('/') def index(): return {'hello': 'world'} @app.route('/cities/{city}') def state_of_city(city): try: return {'state': CITIES_TO_STATE[city]} except KeyError: raise BadRequestError("Unknown city '%s', valid choices: %s" % ( city, ', '.join(CITIES_TO_STATE.keys())))
Book, patron, and lending data is accessed through a serverless Amazon Aurora database. This file is deployed to AWS Lambda as part of the Chalice deployment. """ import logging import urllib.parse from chalice import Chalice from chalice.app import RequestTimeoutError import chalicelib.library_data logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) app = Chalice(app_name='library_api') app.debug = True # Set this to False for production use. _STORAGE = None def get_storage(): """Creates or gets the storage object that calls the database.""" global _STORAGE if _STORAGE is None: _STORAGE = chalicelib.library_data.Storage.from_env() return _STORAGE def storage_timeout(func): def _timeout(*args, **kwargs): try:
import hashlib import hmac import json import os import boto3 from chalice import BadRequestError, Chalice, UnauthorizedError DEBUG = os.environ.get('DEBUG', '') in [1, '1', 'True', 'true'] SECRET = os.environ.get('SECRET') app = Chalice(app_name='github-webhooks') app.debug = DEBUG SNS = boto3.client('sns') def validate_signature(request): """Validate that the signature in the header matches the payload.""" if SECRET is None: return try: signature = request.headers['X-Hub-Signature'] _, sha1 = signature.split('=') except KeyError: raise BadRequestError() digest = hmac.new(SECRET, request.raw_body, hashlib.sha1).hexdigest() if not hmac.compare_digest(digest, sha1.encode('utf-8')): raise UnauthorizedError()
# Core imports import os from chalice import Chalice # App level imports from chalicelib.utils.response import custom_response from chalicelib.utils.config import get_config_env from chalicelib.utils.exceptions import ExceptionNotFound from chalicelib.utils.exceptions import ExceptionHandler from chalicelib.utils.cors import cors_config from chalicelib.resources.message import MessageResource # Main app = Chalice(app_name='chaski-services-email') app.debug = eval(os.getenv('DEBUG')) @app.route('/messages', methods=['POST'], cors=cors_config) def messages(): try: request = app.current_request resource = MessageResource(get_config_env(), app) resource_method = getattr(resource, 'on_{}'.format(request.method.lower())) response = resource_method(request) except (ExceptionHandler, ExceptionNotFound) as e: response = custom_response(409, str(e)) return response
from chalice import Chalice, CognitoUserPoolAuthorizer, BadRequestError, NotFoundError from wfapi.error import WFLoginError from wfapi import Workflowy import boto3 from decouple import config import email # Chalice application config app = Chalice(app_name='personalstats') app.debug = config('DEBUG', default=False, cast=bool) # Authorizer for most endpoints authorizer = CognitoUserPoolAuthorizer( config('COGNITO_USER_POOL_NAME'), provider_arns=[config("COGNITO_USER_POOL_ARN")]) # Cognito client for getting users from the backend cognito_client = boto3.client('cognito-idp') dynamo_db = boto3.client('dynamodb', region_name='us-west-1') s3_client = boto3.client('s3') # Utilty function for rendering the nodes from Workflowy (should be made memory save (with an iterator?)) def render_nested_json(root, indent=0): node = { "name": root.name, "uuid": root.projectid, "last_modified": str(root.last_modified) } if root.children: node['children'] = [] indent += 1
import os from chalice import Chalice from chalicelib.v1_routes import v1_routes from chalicelib.model.models import EventTable, LockTable import logging for db_instance in [EventTable, LockTable]: if not db_instance.exists(): db_instance.create_table(read_capacity_units=1, write_capacity_units=1, wait=True) app = Chalice(app_name="timereport_backend") app.register_blueprint(v1_routes) app.debug = os.getenv("BACKEND_DEBUG", False) log_level = logging.DEBUG if app.debug else logging.INFO app.log.setLevel(log_level)
import os import json import urllib import boto3 from chalice import Chalice, Response from chalicelib.modules.helpers import logger, EXCHANGE_RATES_FILE_NAME from chalicelib.modules.telegram import sendMessage, answerInlineQuery app = Chalice(app_name='unitconversionbot') app.debug = os.environ.get('DEBUG', not os.environ.get('AWS_REGION')) @app.route('/') def index(): return Response( status_code=301, body='', headers={'Location': 'https://telegram.me/UnitConversionBot'}) @app.route('/webhook', methods=['POST']) def telegram_webhook(): request = app.current_request body = request.json_body or {} logger.debug(body) if 'message' in body: response = sendMessage(body) elif 'inline_query' in body: response = answerInlineQuery(body) else:
import os from boto3.session import Session from chalice import Chalice from chalicelib.storage import Storage from chalicelib.sender import Sender from chalicelib.handler import Handler app = Chalice(app_name='latinChat') try: app.debug = eval(os.getenv("DEBUG")) app.websocket_api.session = Session() app.experimental_feature_flags.update(['WEBSOCKETS']) STORAGE = Storage.from_env() SENDER = Sender(app, STORAGE) HANDLER = Handler(STORAGE, SENDER) except Exception as e: print(e) @app.on_ws_connect() def connect(event): print('connect') print('ID: ' + event.connection_id) STORAGE.create_connection(event.connection_id) @app.on_ws_disconnect() def disconnect(event):
import os import random from chalice import Chalice, CORSConfig, NotFoundError, BadRequestError from chalicelib import apigateway from chalicelib import gh_oauth from chalicelib import s3 from chalicelib import sdb from chalicelib import settings from chalicelib import utils app = Chalice(app_name=settings.APP_NAME) app.debug = settings.DEBUG cors_config = CORSConfig( allow_origin=os.environ.get('CORS_ALLOW_ORGIN', settings.CORS_ALLOW_ORGIN), max_age=86400, ) @app.route('/') def index(): return 'GROT2 server' @app.route('/gh-oauth', cors=cors_config) def gh_oauth_endpoint(): gh_code = app.current_request.query_params.get('code', None) if not gh_code: raise BadRequestError('no code')
DOCTYPES = { 'data_obj': os.environ.get('DATA_OBJ_DOCTYPE', 'meta'), 'data_bdl': os.environ.get('DATA_BDL_DOCTYPE', 'databundle'), } try: es_host = os.environ['ES_HOST'] except KeyError: raise RuntimeError("You must specify the domain name of your ElasticSearch" " instance with the ES_HOST environment variable.") es_region = os.environ.get('ES_REGION', DEFAULT_REGION) access_token = os.environ.get('ACCESS_KEY', DEFAULT_ACCESS_TOKEN) client = ESConnection(region=es_region, host=es_host, is_secure=False) app = Chalice(app_name='dos-azul-lambda') app.debug = os.environ.get('DEBUG', False) == 'True' base_path = '/ga4gh/dos/v1' @app.route('/', cors=True) def index(): resp = make_es_request(method='GET', path='/') return resp.read() @app.route('/test_token', methods=["GET", "POST"], cors=True) def test_token(): """ A convenience endpoint for testing whether an access token is active or not. Will return a JSON with a key `authorized`
from chalice import Chalice, Response from chalicelib.controllers import ( my_first_controller ) app = Chalice(app_name='app') app.debug = True # ! remove in prod @app.route('/', cors=True, methods=['GET','POST', 'PUT', 'DELETE']) def route_my_first_controller(): req = app.current_request.json_body return my_first_controller.main() @app.route('/books', methods=['GET', 'POST']) def books_route(): request = app.current_request if request.method == 'GET': return [ dict(book_id=1), dict(book_id=2) ] elif request.method == 'POST': return Response(body=None, headers=dict(Location='/books/3'), status_code=201) @app.route('/books/{book_id}', methods=['GET', 'PUT', 'DELETE']) def books_route(book_id): request = app.current_request
from chalice import Chalice, AuthResponse from chalicelib.noauth import noauth # blueprints import json import time from uuid import uuid4 # for importing .env variables import os from dotenv import load_dotenv load_dotenv() # take environment variables from .env accessible with os.environ.get['NAME'] app = Chalice(app_name='poker-backend-api') app.register_blueprint(noauth, url_prefix="/noauth") # blueprints app.debug = True # DEBUG # app.log.info(somethingGoesHere) @app.middleware('http') def inject_time(event, get_response): start = time.time() response = get_response(event) body = response.body body_obj = json.loads(body) if type(body) == str else body total = time.time() - start body_obj.setdefault('metadata', {})['duration'] = total body_obj.setdefault('metadata', {})['uuid'] = str(uuid4()) response.body = body_obj return response @app.authorizer() def basic_auth_insecure(auth_request):
import os, logging from chalice import Chalice log_level = logging.getLevelName(os.environ.get("LOG_LEVEL", "INFO")) logging.basicConfig(level=log_level) logging.getLogger().setLevel(log_level) app = Chalice(app_name='chalice-app-template') app.debug = True if log_level == logging.DEBUG else False logger = logging.getLogger(__name__) @app.route('/') def index(): app.log.debug("This is a debug logging test with the app logger") app.log.error("This is an error logging test with the app logger") logger.debug("This is a debug logging test with the module logger") logger.error("This is an error logging test with the module logger") return {'hello': 'world'} # The view function above will return {"hello": "world"} # whenever you make an HTTP GET request to '/'. # # Here are a few more examples: # # @app.route('/hello/{name}') # def hello_name(name): # # '/hello/james' -> {"hello": "james"}
import uuid app = Chalice(app_name='GameMicroservice') aws_account_id = boto3.client('sts').get_caller_identity().get('Account') region = os.getenv('region', 'us-east-1') iot_table = os.getenv('iot_table', 'iot_racer') vehicles = int(os.getenv('vehicles', '4')) newround = os.getenv('next_round', 'new_round') vehicle_list = ['red', 'blue', 'white', 'black'] sns_base = 'arn:aws:sns:us-east-1:' topic_unlock_arn = sns_base + aws_account_id + os.getenv( 'topic_unlock', ':vehicle_unlock') topic_vehicle_location = sns_base + aws_account_id + os.getenv( 'vehicle_location', ':vehicle_location') app.debug = os.getenv('DEBUG', True) vehicle_home = { 'red': { 'x': '0', 'y': '0', 'facing': 'S', 'vehicleid': 1, 'it': True }, 'blue': { 'x': '0', 'y': '5', 'facing': 'N', 'vehicleid': 2, 'it': False
import base64 import uuid from subprocess import Popen, PIPE import boto3 from chalice import BadRequestError, Chalice app = Chalice(app_name='thumbnail-service') app.debug = True # TODO: Disable on production S3 = boto3.client('s3') S3_BUCKET = '' # TODO: Replace with valid bucket name @app.route('/', methods=['POST']) def index(): body = app.current_request.json_body image = base64.b64decode(body['data']) format = {'jpg': 'jpeg', 'png': 'png'}[body.get('format', 'jpg').lower()] mode = { 'max': '', 'min': '^', 'exact': '!' }[body.get('mode', 'max').lower()] width = int(body.get('width', 128)) height = int(body.get('height', 128)) cmd = [ 'convert', # ImageMagick Convert '-', # Read original picture from StdIn
from chalice import Chalice from chalice import Response from decouple import config from chalicelib.apps import cron_routes from chalicelib.apps import dashboards_routes app = Chalice(app_name="chalice-app-template") app.debug = config("DEBUG", default=True, cast=bool) run_cron = config("RUN_CRON", default=False, cast=bool) app.log.setLevel(config("LOG_LEVEL", default="DEBUG")) app.register_blueprint(dashboards_routes) if run_cron: app.register_blueprint(cron_routes) @app.route("/") def index(): return Response(body={"running": "ok"}, status_code=200, headers={"Content-Type": "application/json"})
import os from chalice import Chalice from chalicelib.lib import dynamo_lock, dynamo_event from chalicelib.model import Dynamo import logging app = Chalice(app_name='timereport_backend') app.debug = os.getenv('BACKEND_DEBUG', False) log_level = logging.DEBUG if app.debug else logging.INFO app.log.setLevel(log_level) db_event = Dynamo.EventModel db_lock = Dynamo.LockModel # create tables for db in [db_event, db_lock]: if not db.exists(): app.log.debug(f"Creating db table: {db.Meta.table_name}") db.create_table(read_capacity_units=1, write_capacity_units=1, wait=True) @app.route('/table-name', cors=True) def test_name(): """ :return: table name """ return { 'name': [ dynamo_event.dynamoboto.table.name,
import base64 import uuid from subprocess import Popen, PIPE import boto3 from chalice import BadRequestError, Chalice app = Chalice(app_name='thumbnail-service') app.debug = True # TODO: Disable on production S3 = boto3.client('s3') S3_BUCKET = '' # TODO: Replace with valid bucket name @app.route('/', methods=['POST']) def index(): body = app.current_request.json_body image = base64.b64decode(body['data']) format = {'jpg': 'jpeg', 'png': 'png'}[body.get('format', 'jpg').lower()] mode = {'max': '', 'min': '^', 'exact': '!'}[body.get('mode', 'max').lower()] width = int(body.get('width', 128)) height = int(body.get('height', 128)) cmd = [ 'convert', # ImageMagick Convert '-', # Read original picture from StdIn '-auto-orient', # Detect picture orientation from metadata '-thumbnail', '{}x{}{}'.format(width, height, mode), # Thumbnail size '-extent', '{}x{}'.format(width, height), # Fill if original picture is smaller than thumbnail
CONFIG = { "DEBUG": os.environ.get("DEBUG", "") in [1, "1", "True", "true"], "SECRET": os.environ.get("SECRET"), "S3_REGION": os.environ.get("S3_REGION", "eu-west-1"), "HASHLIB_BLACKLIST": parse_hashlib_blacklist( os.getenv("HASHLIB_BLACKLIST", DEFAULT_HASHLIB_BLACKLIST)), } app = Chalice(app_name="github-webhooks") app.debug = CONFIG["DEBUG"] SNS = boto3.client("sns", region_name=CONFIG["S3_REGION"]) def validate_signature(request): """Validate that the signature in the header matches the payload.""" if CONFIG["SECRET"] is None: return try: signature = request.headers["X-Hub-Signature"] hashname, hashval = signature.split("=") except (KeyError, ValueError): raise BadRequestError() if (hashname in CONFIG["HASHLIB_BLACKLIST"]) or (
"""Rest API for Demo.""" from chalice import Chalice from chalice import Response from demo_dao import DemoDao from util.logger_utility import LoggerUtility APP = Chalice(app_name='ramit-test') APP.debug = True @APP.route('/info', methods=['POST']) def info(): """Info on user.""" # Set log level LoggerUtility.set_level() try: request = APP.current_request demo_dao = DemoDao(request.json_body) response = demo_dao.info() LoggerUtility.log_info('API Invoke sucessfully!') return Response(response, status_code=200) except UserNotFoundException as user_not_found_exception: body = { 'Code': '404 - UserNotFound', 'Message': str(user_not_found_exception) } return Response(body, status_code=404) except Exception as exception: body = {'Code': '500- InternalServerError', 'Message': str(exception)} return Response(body, status_code=500)
from json import dumps import logging from chalice import Chalice import credstash from howdoi import howdoi as hdi import requests logger = logging.getLogger() logger.setLevel(logging.INFO) app = Chalice(app_name='howdoi_') app.debug = False def _call_howdoi(query): parser = hdi.get_parser() args = vars(parser.parse_args(query.split(' '))) return hdi.howdoi(args) def _process_text(text): """usage: howdoi [-h] [-p POS] [-a] [-l] [-c] [-n NUM_ANSWERS] [-C] [-v] [QUERY [QUERY ...]] instant coding answers via the command line positional arguments: QUERY the question to answer optional arguments: -h, --help show this help message and exit -p POS, --pos POS select answer in specified position (default: 1)
from chalice import Chalice from chalice import BadRequestError, NotFoundError from requests import get from tempfile import TemporaryFile, TemporaryDirectory from os import chdir, getcwd, path from chalicelib.erc20 import erc20 from io import StringIO from contextlib import redirect_stdout from logging import INFO app = Chalice(app_name='erc20-verifier') app.log.setLevel(INFO) LOCAL = False ETHERSCAN_API_KEY = '' app.debug = LOCAL @app.route('/verify/{address}', methods=['GET'], cors=True) def verify(address): # Validate input if not address or len(address) == 0: raise BadRequestError("Address not set") if len(address) != 40 and len(address) != 42: raise BadRequestError("Malformed address %s" % (address, )) app.log.info("Request %s" % (address, )) # Get source from etherscan name, source, compiler = get_name_and_source(address)
from chalice import Chalice import os import requests from jira import Issue app = Chalice(app_name='JIRACrossTenant') # set to True if debugging app.debug = False @app.route('/', methods=['POST']) def index(): payload = app.current_request.json_body issue = Issue(payload)
aws_secret_access_key=credentials.secret_key, aws_token=credentials.token, aws_host=es_host, aws_region=session.region_name, aws_service='es' ) es = elasticsearch.Elasticsearch( hosts=[{'host': es_host, 'port': 443}], http_auth=awsauth, use_ssl=True, verify_certs=True, connection_class=elasticsearch.RequestsHttpConnection ) app = Chalice(app_name='dos-azul-lambda') app.debug = os.environ.get('DEBUG', 'True') == 'True' base_path = '/ga4gh/dos/v1' @app.route('/', cors=True) def index(): return Response(body='<h2>Welcome to Dos-Azul-Lambda! ' 'Find the docs ' '<a href="https://ga4gh.github.io/data-repository-service-schemas/">here</a></h2>', status_code=200, headers={'Content-Type': 'text/html'}) @app.route('/test_token', methods=["GET", "POST"], cors=True) def test_token():
import boto3 from chalice import Chalice, NotFoundError, Response import requests app = Chalice(app_name='chalice-app') app.debug = True # disable for prod BUCKET = 'soft-brush-images' index_html= """<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Upload</title> </head> <body> <body> <form method="post" enctype="multipart/form-data" action="upload"> <input type="file" name="file"> <input type="submit" value="Upload"> </form> </body> </body> </html>""" image_html = """<!DOCTYPE html> <html lang="en"> <head>
import hashlib import hmac import json import os import boto3 from chalice import BadRequestError, Chalice, UnauthorizedError CONFIG = { 'DEBUG': os.environ.get('DEBUG', '') in [1, '1', 'True', 'true'], 'SECRET': os.environ.get('SECRET'), 'S3_REGION': os.environ.get('S3_REGION', 'eu-west-1'), } app = Chalice(app_name='github-webhooks') app.debug = CONFIG['DEBUG'] SNS = boto3.client('sns', region_name=CONFIG['S3_REGION']) def validate_signature(request): """Validate that the signature in the header matches the payload.""" if CONFIG['SECRET'] is None: return try: signature = request.headers['X-Hub-Signature'] _, sha1 = signature.split('=') except (KeyError, ValueError): raise BadRequestError() digest = hmac.new(CONFIG['SECRET'].encode(), request.raw_body.encode(), hashlib.sha1) \ .hexdigest()
from chalice import Chalice from chalicelib import intelligent_assistant_service import json ##### # chalice app configuration ##### app = Chalice(app_name='Capabilities') app.debug = True ##### # services initialization ##### assistant_name = 'ContactAssistant' assistant_service = intelligent_assistant_service.IntelligentAssistantService( assistant_name) ##### # RESTful endpoints ##### @app.route('/contact-assistant/user-id/{user_id}/send-text', methods=['POST'], cors=True) def send_user_text(user_id): request_data = json.loads(app.current_request.raw_body) message = assistant_service.send_user_text(user_id, request_data['text']) return message
from collections import Counter import requests import json import re import boto3 import os import config app = Chalice(app_name='AdvanceDigital') BUCKET = config.awsConfig['bucketName'] s3Client = boto3.client('s3', aws_access_key_id=config.awsConfig['accessKey'] , aws_secret_access_key=config.awsConfig['secretKey'] ) NEWS_URL = config.newsConfig['url'] API_KEY = config.newsConfig['key'] SOURCES_LIST = config.newsConfig['sources'] app.debug = config.settings['debugMode'] DEFAULT_WORD_LIMIT = config.newsConfig['defaultWordLimit'] DEFAULT_MIN_WORD_LEN = config.newsConfig['defaultMinWordLen'] INDEX = config.awsConfig['index'] dirPath = os.path.dirname(os.path.realpath(__file__)) @app.route('/status') def getStatus(): awsStatus = "err" newsStatus = "err" try: s3Client.head_bucket(Bucket=BUCKET) awsStatus = "Good" except Exception as e: awsStatus = str(e)