def test_can_invoke_handler_from_blueprint(): bp = Blueprint('testblueprint') @bp.lambda_function() def my_foo(event, context): return {'event': event} app = Chalice('myapp') app.register_blueprint(bp) with Client(app) as client: response = client.lambda_.invoke('my_foo', {'hello': 'world'}) assert response.payload == {'event': {'hello': 'world'}}
import logging from chalice import Chalice from chalicelib.lambda_function_1 import lambda_function_1_blueprint from chalicelib.lambda_function_2 import lambda_function_2_blueprint from chalicelib.lambda_function_3 import lambda_function_3_blueprint logging.basicConfig(level=logging.INFO) app = Chalice(app_name='serverless_framework') app.log.setLevel(logging.INFO) app.experimental_feature_flags.update(['BLUEPRINTS']) app.register_blueprint(lambda_function_1_blueprint) app.register_blueprint(lambda_function_2_blueprint) app.register_blueprint(lambda_function_3_blueprint)
# # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. from chalice import Chalice from chalicelib.modules import bp as modules_bp app = Chalice(app_name="terraform-registry") app.experimental_feature_flags.update(["BLUEPRINTS"]) app.register_blueprint(modules_bp, url_prefix="/modules") @app.route("/.well-known/terraform.json") def discovery(): """The Terraform Registry Service Discovery Protocol ref: https://www.terraform.io/docs/internals/remote-service-discovery.html#discovery-process """ return {"modules.v1": f"/modules/"}
from chalicelib.audit_app.audit_controller import audit_app from chalicelib.feedback_app.feedback_controller import feedback_app app = Chalice(app_name='audit-feedback') app.debug = True _USER_AUDIT_DB = None _SESSION_AUDIT_DB = None _FEEDBACK_DB = None _USER_ROLES_DB = None _SESSION_ROLES_DB = None _USER_ROLES = None _SESSION_ROLES = None @app.route('/') def index(): return {'hello': 'world'} @app.route('/api/custom-auth', methods=['GET'], authorizer=global_auth.authorizer) def authenticated(): return {"success": True} app.register_blueprint(audit_app) app.register_blueprint(feedback_app) app.register_blueprint(roles_app)
from chalice import Chalice import boto3 from chalicelib import Address, jsonify, dynamoDb, Authenticator from chalicelib.config import Config from chalicelib.blueprint import BluePrintRegister from chalicelib.decorators import jwt_required app = Chalice(app_name='identity-Manager') app.register_blueprint(BluePrintRegister.bluePrintIns) dynamodb = boto3.resource('dynamodb') @app.route('/v1/get-token', methods=["POST"]) def get_token(): username = app.current_request.json_body.get('username') password = app.current_request.json_body.get('password') confirm = app.current_request.json_body.get('confirm') dydbTableObj = dynamodb.Table(Config.service_user_holder_table) resp = dydbTableObj.get_item(Key={'username': username}) try: Item = resp.get('Item') if not Item.get('password') == password or not Item.get( 'confirm') == confirm: return jsonify(message='Invalid password/confirm', is_token=False) if not Item.get('is_active'): return jsonify(message='Inactive username', is_token=False) except: return jsonify(message='Invalid username', is_token=False) jwtToken = (Authenticator.create_token(username)).decode('utf-8') return jsonify(jwt_token=jwtToken, is_token=True)
import os from chalice import Chalice from controller.controller import api from chalicelib import env app = Chalice(app_name='handson') app.register_blueprint(api) # print(env.get_parameters(os.environ['testuser'])) # print(env.get_parameters(os.environ['testpassword'])) print(env.TESTUSER) print(env.TESTPASSWORD) @app.route('/') def index(): return {'hello': 'world'} @app.lambda_function() def custom_lambda_function001(event, context): # Anything you want here. return {'body': 'lambda_faction001'} @app.lambda_function(name='MyFunction') def other_lambda_function(event, context): # Anything you want here. return {'body': 'lambda_MyFunction'}
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"})
from chalice import Chalice from chalicelib.fixtures import fixtures from chalicelib.historical import history from chalicelib.match_predictions import predictions app = Chalice(app_name='football_predictions') app.register_blueprint(fixtures) app.register_blueprint(history) app.register_blueprint(predictions)
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)
from chalice.app import Response from chalicelib.api.swagger_api import swagger_api from chalicelib.utils.swagger_utls import get_swagger_ui from chalice import Chalice import logging # Set application name app = Chalice(app_name='aws-chalice-template') # Register blueprint app.register_blueprint(swagger_api) # Set logger logger = logging.getLogger() logger.setLevel(logging.INFO) @app.route("/", methods=["GET"]) def get_doc(): """Get Swagger UI Main Page Returns: str: text/html for Swagger UI page """ html = get_swagger_ui(app) return Response( body=html, status_code=200, headers={"Content-Type": "text/html"}, )
from chalice import Chalice from chalicelib.router import * app = Chalice(app_name='employee_det') app.register_blueprint(BlueprintRegister.router) app.api.cors = True app.debug = True
from chalice import Chalice, Response, AuthResponse from chalicelib.routes.main import main_routes from chalicelib.routes.user import user_routes from chalicelib.routes.taxi import taxi_routes from chalicelib.model.FavouritesTaxiStand import FavouritesTaxiStandModel import jwt import os import uuid from dotenv import load_dotenv load_dotenv() app = Chalice(app_name='singapore-taxi-api') app.register_blueprint(main_routes) app.register_blueprint(user_routes) app.register_blueprint(taxi_routes) @app.authorizer() def authorizer(auth_request): response = {} token = auth_request.token print('token = ', token) principal_id = 'user' auth_success = False if token: token = token.replace('Bearer ', '') decoded = jwt.decode(token, os.getenv(
from chalice import Chalice from chalicelib.audit_app.audit_controller import audit_app from chalicelib.roles.roles_controller import roles_app from chalicelib.session_app.session_controller import session_app from chalicelib.user_app.user_controller import user_app from chalicelib.auth import auth_app from chalicelib import global_auth app = Chalice(app_name='sessions-app') app.debug = True @app.route('/', cors=global_auth.cors_config) def index(): return {'hello': 'world'} # @app.route('/needs-auth', authorizer=auth_app.authorizer()) # def needs_auth(): # return {'success': True} app.register_blueprint(audit_app) app.register_blueprint(roles_app) app.register_blueprint(session_app) app.register_blueprint(user_app) app.register_blueprint(auth_app)
(data, container) = get_container_data(org, c['name'], config) generator = ScriptGenerator(os.environ.get('OTM_URL'), os.environ.get('COLLECT_URL')) generator.import_config(data) script = generator.generate() uploader = S3Uploader(None, script_bucket=os.environ.get('OTM_BUCKET'), otm_path=os.environ.get('OTM_URL')) uploader.upload_script(prefix + c['name'] + '.js', script) # save freezed data s3.Object(os.environ.get('OTM_BUCKET'), 'freezed.json').put(Body=json.dumps(freezed_orgs), ContentType='application/json') return Response(body='', status_code=204) app.register_blueprint(container_routes, url_prefix='/orgs/{org}/containers') app.register_blueprint(swagger_doc_routes, url_prefix='/orgs/{org}/containers/{name}/swagger_doc') app.register_blueprint(stats_routes, url_prefix='/orgs/{org}/containers/{name}/stats') plugins = json.loads(os.environ.get('OTM_PLUGINS'), encoding='utf-8') for plugin in plugins: module = importlib.import_module('chalicelib.otmplugins.' + plugin['package'] + '.' + plugin['module']) app.register_blueprint(module.plugin_app, url_prefix=plugin['urlPrefix'])
from chalice import Chalice from chalice import BadRequestError from chalice import NotFoundError import json from urllib.parse import urlparse, parse_qs from chalicelib.routes import root app = Chalice(app_name='helloworld') app.debug = True app.experimental_feature_flags.update(['BLUEPRINTS']) app.register_blueprint(root) @app.route('/introspect') def introspect(): return app.current_request.to_dict() ##@app.route('/', methods=['POST'], ## content_types=['application/x-www-form-urlencoded']) ##def index(): ## parsed = parse_qs(app.current_request.raw_body_decode()) ## 'states': parsed.get('states', []) ## } # The view function above will return {"hello": "world"} # whenever you make an HTTP GET request to '/'. # # Here are a few more examples: #
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):