from chalice import Chalice from chalicelib import storage_service from chalicelib import recognition_service from chalicelib import translation_service import base64 import json ##### # chalice app configuration ##### app = Chalice(app_name='Capabilities') app.debug = True ##### # services initialization ##### storage_location = 'contents.aws.ai' storage_service = storage_service.StorageService(storage_location) recognition_service = recognition_service.RecognitionService(storage_service) translation_service = translation_service.TranslationService() ##### # RESTful endpoints ##### @app.route('/images', methods=['POST'], cors=True) def upload_image(): """processes file upload and saves file to storage service""" request_data = json.loads(app.current_request.raw_body) file_name = request_data['filename']
# TODO: Add additional exception and response codes # TODO: Narrow exception scopes # TODO: Better way to bubble exceptions to lambda helper class # TODO: Normalize pattern for referencing URI params inside a function # TODO: Move global_attributes list to a top level variable ''' except ClientError as e: print(e.response['Error']['Message']) ''' logger = logging.getLogger('boto3') logger.setLevel(logging.INFO) app_name = 'dataplaneapi' app = Chalice(app_name=app_name) # DDB resources dataplane_table_name = os.environ['DATAPLANE_TABLE_NAME'] dynamo_client = boto3.client('dynamodb') dynamo_resource = boto3.resource('dynamodb') # S3 resources dataplane_s3_bucket = os.environ['DATAPLANE_BUCKET'] # Cognito resources # From cloudformation stack cognito_user_pool_arn = os.environ['USER_POOL_ARN'] # TODO: Should we add a variable for the upload bucket?
from pythonjsonlogger import jsonlogger #APP ENVIRONMENTAL VARIABLES REGION = "us-east-1" APP = "nlp-api" NLP_TABLE = "nlp-table" #intialize logging log = logging.getLogger("nlp-api") LOGHANDLER = logging.StreamHandler() FORMMATTER = jsonlogger.JsonFormatter() LOGHANDLER.setFormatter(FORMMATTER) log.addHandler(LOGHANDLER) log.setLevel(logging.INFO) app = Chalice(app_name='nlp-api') app.debug = True def dynamodb_client(): """Create Dynamodb Client""" extra_msg = {"region_name": REGION, "aws_service": "dynamodb"} client = boto3.client('dynamodb', region_name=REGION) log.info("dynamodb CLIENT connection initiated", extra=extra_msg) return client def dynamodb_resource(): """Create Dynamodb Resource"""
import boto3 import json import datetime from datetime import datetime from chalice import Chalice from chalice import CORSConfig from chalice import CognitoUserPoolAuthorizer from chalice import BadRequestError from chalice import NotFoundError from chalice import ChaliceViewError app = Chalice(app_name='mygame_app') app.debug = True print('Loading function') dynamodb_client = boto3.client('dynamodb') cors_config = CORSConfig( # allow_origin='http://localhost:63342', # allow_origin='http://mygame.jimhough.com.s3-website-us-east-1.amazonaws.com', allow_origin='http://mygame.jimhough.com', allow_headers=['Access-Control-Allow-Origin', 'X-Special-Header', 'User'], max_age=600, expose_headers=['X-Special-Header'], allow_credentials=True)
from __future__ import print_function #Code should work with Python 2 or 3 from chalice import Chalice from aws_xray_sdk.core import xray_recorder from aws_xray_sdk.core import patch import hmac import hashlib import base64 import sys import requests import os import boto3 import json patch(('boto3', 'requests')) app = Chalice(app_name='swapcaser') app.debug = True try: client = boto3.client('ssm') response = client.get_parameter( Name='/unicornrentals/swapcaser/externalservice') SWAPCASESERVICE = response['Parameter']['Value'] response = client.get_parameter(Name='/unicornrentals/team/teamid') TEAMID = response['Parameter']['Value'] response = client.get_parameter(Name='/unicornrentals/team/teamhash') HASH = response['Parameter']['Value'] except: print("SSM unavailable - do you have the TeamRole attached") print("You could setup envars") SWAPCASESERVICE = os.getenv('SWAPCASESERVICE', False)
import json import logging import sys from chalice import Chalice from chalicelib import service from chalicelib.helpers import DateTimeEncoder app = Chalice(app_name='prod-api') app.debug = True logger = logging.getLogger() logger.setLevel(logging.INFO) @app.route('/') def index(): return {'hello': 'world'} @app.route('/project', methods=['GET', 'POST'], cors=True) def projects(): request = app.current_request if request.method == 'GET': resp = service.get_all_projects() try: json_resp = json.dumps(resp) except:
from chalice import Chalice, Response import datetime import boto3 app = Chalice(app_name='chalice_helloworld') client = boto3.client('dynamodb') @app.route('/', methods=['GET']) def list(): response = client.scan( TableName="TweetyComments" ) html = "<html><head><title>TweetyComments</title><style>tbody tr:nth-child(odd) {background: #eee;}</style></head><body><table>" for item in response['Items']: row = "<tr border=''>" row += "<td>" + item['content']['S'] + "</td>" row += "<td><a href='"+ item['url']['S'] + "'>" + item['url']['S'] + "</a></td>" row += "<td><input type='submit' value='Jira' /></td>" row += "<td><input type='submit' value='Done' /></td>" row += "</td>" html += row html += "</table></body></html>" return Response(body=html, status_code=200, headers={'Content-Type': 'text/html'}) @app.route('/store', methods=['POST'], cors=True) def store(): comment = app.current_request.json_body
from chalice import Chalice import chalicelib.database.rd as redis import os import logging as log import chalicelib.json_proto as proto import chalicelib.users as users import chalicelib.movies as movies import chalicelib.reviews as reviews import chalicelib.common import json app = Chalice(app_name='adb-mr') app.debug = True def init_log(log): log_level = os.getenv('DEFAULT_LOG_LEVEL') or 'INFO' level = getattr(log, log_level) if hasattr(log, log_level) else log.WARNING print(f"log level: {log_level}") log.basicConfig( level=level, format='%(asctime)s %(levelname)-8s [%(name)s.%(funcName)s:%(' 'lineno)d] %(message)s', datefmt='%Y-%m-%d %H:%M:%S') logger = log.getLogger() logger.setLevel(level=log_level) init_log(log)
from chalice import Chalice from chalice import BadRequestError, Response app = Chalice(app_name="views") @app.route("/") def badrequest(): raise BadRequestError("This is a default request") @app.route("/badrequest") def badrequest(): raise BadRequestError("This is a bad request") @app.route("/badrequest1") def badrequest1(): return Response( body="This is a custom bad request", status_code=400, headers={"Content-Type": "text/plain"}, ) @app.route("/resource/{value}", methods=["PUT"]) def put_test(value): return {"value": value} @app.route("/myview", methods=["POST", "PUT"])
from chalice import Chalice, Response import chalicelib.constants app = Chalice(app_name='aws-chalice-echosvc') @app.route('/') def index(): return {'hello': 'world'} @app.route('/echo') def echo(): ctx = app.current_request.to_dict() return {'source': (ctx['context']['identity']['sourceIp'])} @app.route('/hello/{name}') def hello(name): return {'hello': name} @app.route('/rickroll') def rick(): return Response(body='', status_code=301, headers={'Location': URL})
import os import boto3 from chalice import Chalice app = Chalice(app_name=os.environ['APP_NAME']) app.websocket_api.session = boto3.session.Session() app.experimental_feature_flags.update([ 'WEBSOCKETS' ]) ddb = boto3.client('dynamodb') # This comment is to cause a change which triggers a redeployment # of the Lambda Function, this is needed to properly test redeployment. @app.on_ws_message() def message(event): ddb.put_item( TableName=os.environ['APP_NAME'], Item={ 'entry': { 'N': event.body }, }, )
from chalice import BadRequestError, Chalice, NotFoundError from chalicelib import database, utils from chalice import CognitoUserPoolAuthorizer import os import logging authorizer = CognitoUserPoolAuthorizer( 'ChaliceUserPool', provider_arns=[os.environ['USER_POOL_ARN']]) app = Chalice(app_name='images-api') app.log.setLevel(logging.INFO) # TABLE_NAME = 'Images' # すべてのImageを取得する @app.route('/images', methods=['GET'], cors=True, authorizer=authorizer) def get_all_images(): return database.get_all_images() # 指定されたIDのImageを取得する @app.route('/images/{image_id}', methods=['GET'], cors=True, authorizer=authorizer) def get_image(image_id): app.log.debug("success") image = database.get_image(image_id) if image: return image else:
from chalice import Chalice,NotFoundError,BadRequestError from chalicelib import database app = Chalice(app_name='tracking') @app.route('/track/{name}',methods=["GET"],cors=True) def tracks(name): return database.track(name)
from chalice import Chalice, Response import requests import os import jinja2 import boto3 import random import string app = Chalice(app_name='adx') def render(tpl_path, context): '''Helper to render jinja template''' path, filename = os.path.split(tpl_path) return jinja2.Environment(loader=jinja2.FileSystemLoader( path or "./")).get_template(filename).render(context) @app.route('/index/{params}', methods=['GET'], cors=True) def index(params): '''Call public api, render data in browser''' response = requests.get( "https://www.alphavantage.co/query?function=ADX&symbol={}&interval=daily&time_period=10&apikey=K87BB8H31SVY3OBA" .format(params)) data = response.json() time_interval = [] index_rating = [] legend = "ADX graph" for k, v in data['Technical Analysis: ADX'].items(): time_interval.append(k)
# -*- coding: utf-8 -*- from chalice import Chalice import sys import json import logging import os import time app = Chalice(app_name='StockAlarm') @app.route('/') def index(): return {'hello': 'world'} @app.route('/meta') def call_meta(): return app.current_request.to_dict() @app.route('/alarm', methods=['GET']) def alarm_tickers(): from chalicelib.msg_maker import MsgMaker from chalicelib.alarm_service import alarm_to_slack ''' us-east-1 시간이 적용된다. 하루의 장이 마감이 되면 tickerList 읽어서 Slack으로 알람을 쏴준다. ''' ticker_str = os.environ['tickerList'] # `{"AGG":200,"BND":200}`
from chalice import ( Chalice, Response, CORSConfig, AuthResponse, AuthRoute, ) from chalice import NotFoundError, BadRequestError # from operationsresearch.prepaid import PrepaidSolver from ortools.linear_solver import pywraplp import os app = Chalice(app_name="solver") # Configure CORS Routes # cors_allow_origin = os.getenv("CORS_ALLOW_ORIGIN", "*") cors_allow_origin = "*" cors_config = CORSConfig(allow_origin=cors_allow_origin) # Configure debug output environment = os.getenv("CHALICE_ENVIRONMENT", "development") if environment == "development": app.debug = True class PrepaidSolver: def __init__(self, tiers: dict, target: float): self.solver = pywraplp.Solver( "TierSolver", pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING )
from chalice import Chalice, Response import requests import os app = Chalice(app_name='sentry-badge') app.debug = True #https://api.codacy.com/project/badge/Grade/72a7aaa0e3fd4a8db27607da159d3daa?branch=test @app.route('/{org}/{project}') def index(org, project): print("ORG", org) print("PROJECT", project) AUTH0_TOKEN = "Bearer " + os.getenv('SENTRY_TOKEN') url = "https://app.getsentry.com/api/0/projects/" + org + "/" + project + "/issues/?statsPeriod=24h" print(url) r = requests.get(url, headers={'Authorization': AUTH0_TOKEN}) if r.status_code != 200: raise ValueError("API ERROR: " + url) j = r.json() total = 0 color = "#62d46d" for group in j: total += int(group["count"]) if total > 0: color = "#953b39" dict = { 'error_count': total, 'color' : color} body = ''' <svg xmlns="http://www.w3.org/2000/svg" width="88" height="20"> <linearGradient id="a" x2="0" y2="100%"> <stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
from chalice import Chalice import os import json import urllib.request import logging logger = logging.getLogger() logger.setLevel(logging.INFO) app = Chalice(app_name='slackevent') @app.route('/', methods=['GET']) def index(): return {'hello': 'world'} @app.route('/', methods=['POST']) def hoge(): data = app.current_request.json_body if (data['type'] == 'url_verification'): return url_verification(data) elif (data['type'] == 'event_callback'): if (data['event']['type'] == 'emoji_changed'): return emoji_changed(data['event']) log.warn("unsupported data %s" % data) return { 'unsupported': data } def url_verification(data): if (data['token'] == os.environ["VERIFICATION_TOKEN"]): return {
from chalice import Chalice, Response from urllib import request import urllib.parse import json app = Chalice(app_name='get-a-cat') app.debug = True clientID = "708291774949.843032109105" clientSecret = "da13b7129df5e0ca54e4a5b87f272432" @app.route('/slack/authorizer', methods=['GET']) def slack_authorizer(): try: print('into authorizer component') event = app.current_request.raw_body.decode("utf-8") print('incomming_request: %s' % (event)) message = 'authorization initiated.' response = {'status': 'success', 'message': '%s' % (message)} return Response( body=json.dumps(response), status_code=200, ) except Exception as e: error_msg = 'error msg =%s' % (str(e)) response = {'status': 'error', 'message': '%s' % (error_msg)} return Response( body=json.dumps(response), status_code=500, )
from chalice import Chalice import json import boto3 import logging app = Chalice(app_name='ppnotification') session = boto3.Session(region_name="ap-southeast-1") sns_client = session.client('sns') wnsPlatform = 'arn:aws:sns:ap-southeast-1:734187701565:app/WNS/mobilepushwns' @app.route('/unregisterDevice') def unregisterDevice(): return 'You have success register your device' @app.route('/registerDevice') def registerDevice(event, context): user_id = event['Id'] token_id = event['Token'] user_data = event['User_data'] respone_endpoint = create_application_endpoint(wnsPlatform, token_id, user_data) logging.info('show respone_endpoint') logging.info(respone_endpoint)
import json import datetime import pymysql import boto3 import requests from chalice import Chalice db_host = "iot-centre-rds.crqhd2o1amcg.ap-southeast-1.rds.amazonaws.com" db_name = "360-degree-camera" db_username = "******" db_password = "******" app = Chalice(app_name='360-Degree-Image') @app.route('/sqs', content_types=['application/json'], methods=['POST']) def sqs_service(): sqs = boto3.resource('sqs') queue = sqs.get_queue_by_name(QueueName='DatntQueue') message = app.current_request.raw_body response = queue.send_message(MessageBody=message) return {"status": message}
from chalice import Chalice, Response from botocore.config import Config as bc_Config from botocore.exceptions import ClientError import os from urllib.parse import urlparse, quote_plus from rain_api_core.general_util import get_log from rain_api_core.urs_util import get_urs_url, do_login, user_in_group from rain_api_core.aws_util import get_yaml_file, get_role_session, get_role_creds, check_in_region_request from rain_api_core.view_util import get_html_body, get_cookie_vars, make_set_cookie_headers from rain_api_core.session_util import get_session, delete_session from rain_api_core.egress_util import get_presigned_url, process_varargs, check_private_bucket, check_public_bucket app = Chalice(app_name='egress-lambda') log = get_log() conf_bucket = os.getenv('CONFIG_BUCKET', "rain-t-config") # Here's a lifetime-of lambda cache of these values: bucket_map_file = os.getenv('BUCKET_MAP_FILE', 'bucket_map.yaml') b_map = None public_buckets_file = os.getenv('PUBLIC_BUCKETS_FILE', None) public_buckets = None private_buckets_file = os.getenv('PRIVATE_BUCKETS_FILE', None) private_buckets = None STAGE = os.getenv('STAGE_NAME', 'DEV') header_map = {'date': 'Date', 'last-modified': 'Last-Modified', 'accept-ranges': 'Accept-Ranges', 'etag': 'ETag', 'content-type': 'Content-Type',
import os import json from chalice import Chalice from chalicelib import MESSAGE app = Chalice(app_name='Multifile') filename = os.path.join( os.path.dirname(__file__), 'chalicelib', 'app-config.json') with open(filename) as f: config = json.load(f) @app.route('/') def index(): if config['greet']: return {MESSAGE: 'world'} return {'bye': 'world'}
from numpy import asarray, char from numpy.core.defchararray import find logger.setLevel('CRITICAL') title = os.environ.get('APP_TITLE', 'Lakota') uri = os.environ.get('LAKOTA_REPO', '.lakota') app_prefix = os.environ.get('APP_PREFIX', '') static_prefix = 'static' repo = Repo(['/tmp/lakota-cache', uri]) PAGE_LEN = 20_000 lib_path = Path(__file__).parent / 'chalicelib' tpl_path = lib_path / 'template' static_path = lib_path / 'static' env = Environment(loader=FileSystemLoader([tpl_path])) app = Chalice(app_name='lakota-lambda') app.api.binary_types.extend(['application/json']) uplot_options = { # 'title': '', # 'id': '', # 'class': '', 'width': 900, 'height': 300, 'series': [ {}, { # initial toggled state (optional) 'show': True,
#!/usr/bin/env python import os from chalice import Chalice from chalice import Response from linebot import LineBotApi, WebhookHandler from linebot.models import (MessageEvent, TextMessage, TextSendMessage) from linebot.exceptions import (InvalidSignatureError, LineBotApiError) app = Chalice(app_name='chalice-linebot') line_bot_api = LineBotApi(os.environ['LINEBOT_CHANNEL_ACCESS_TOKEN']) handler = WebhookHandler(os.environ['LINEBOT_CHANNEL_SECRET']) @app.route('/callback', methods=['POST']) def callback(): signature = app.current_request.headers['X-Line-Signature'] body = app.current_request.raw_body.decode('utf-8') try: handler.handle(body, signature) except InvalidSignatureError as e: return Response({'error': e.message}, status_code=400) except LineBotApiError as e: if e.message == 'Invalid reply token': return 'OK' return Response({'error': e.message}, status_code=400) return 'OK'
import sys import boto3 import json from chalice import Chalice from boto3.dynamodb.conditions import Key client = boto3.client('dynamodb') app = Chalice(app_name='ArkanoidScores') @app.route('/score') def get_highest(): response = client.query( TableName='ArkanoidScores', KeyConditionExpression='score', Limit=1, ScanIndexForward=False, ) json_resp = json.dumps(response.get("Items")) return json_resp @app.route('/score', methods=['POST']) def push_score(): parsed = json.loads(app.current_request._body) placeholder = "XXX" client.put_item(TableName='ArkanoidScores', Item={ 'score': { 'N': str(parsed.get('score')) },
from peewee import * from marshmallow_peewee import ModelSchema pg_db = PostgresqlDatabase('postgres', user='******', password='******', host='rds.amazonaws.com', port=5432) class Person(Model): name = CharField() class Meta: database = pg_db # This model uses the "people.db" database. class PersonSchema(ModelSchema): class Meta: model = Person app = Chalice(app_name='marshmellowtest') app.debug = True def initialize_db(): pg_db.connect() pg_db.create_tables([Person], safe = True) pg_db.close() @app.route('/') def index(): initialize_db() Person.create(name='Austin') query = Person.select().where(Person.name == 'Austin').get() schema = PersonSchema() return schema.dump(query)
from chalice import Chalice app = Chalice(app_name='weight-handler') @app.route('/') def index(): 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"} # return {'hello': name} # # @app.route('/users', methods=['POST']) # def create_user(): # # This is the JSON body the user sent in their POST request. # user_as_json = app.current_request.json_body # # We'll echo the json body back to the user in a 'user' key. # return {'user': user_as_json} # # See the README documentation for more examples. #
from chalice import Chalice, AuthResponse, Response from chalicelib.User import User from chalicelib.UserAuthUtility import UserAuthUtility from boto3.dynamodb.types import Binary from decimal import Decimal import botocore import json app = Chalice(app_name='BackendApi') STATUS_CODES = { "ConditionalCheckFailedException": 400, "Unknown": 502 } @app.authorizer() def jwt_auth(auth_request): token = auth_request.token print(token) decoded = UserAuthUtility.decode_jwt_token(token) return AuthResponse(routes=['*'], principal_id=decoded['sub']) @app.route('/register', methods=['POST']) def register(): body = app.current_request.json_body username = body['username'].lower() password = body['password'] first_name = body['first_name'] last_name = body['last_name'] email = body['email'] try:
"""Test app redeploy. This file is copied over to app.py during the integration tests to test behavior on redeploys. """ from chalice import Chalice app = Chalice(app_name='smoketestapp') # Test an unchanged view, this is the exact # version from app.py @app.route('/') def index(): return {'hello': 'world'} # Test same route info but changed view code. @app.route('/a/b/c/d/e/f/g') def nested_route(): return {'redeployed': True} # Test route deletion. This view is in the original # app.py but is now deleted. # @app.route('/path/{name}') # def supports_path_params(name): # return {'path': name}