Esempio n. 1
0
import os

from chalice import Chalice
from jinja2 import Template
import logging

from config import template_directory

logger = logging.getLogger()
logger.setLevel(logging.INFO)

app = Chalice(app_name='personalwebsite')


@app.route('/')
def index():
    template_file = next(file for file in template_directory.iterdir()
                         if 'index.html' == file.name.lower())

    return Template(template_file.read_text()).render(
        cloudfront_url=os.getenv('cloudfront_url'),
        login_url='login',
        logout_url='logout',
        email_me_url='email-me',
        custom_message=None)
Esempio n. 2
0
from chalice import Chalice
import requests
from lxml import html
from newspaper import Config, Article
from random import choice
from json_tricks.np import dump, dumps
from multiprocessing import Process, Pool
import datetime
from pymongo import MongoClient
from bson import ObjectId
import json

app = Chalice(app_name='newsapi2')

app.debug = True
config = Config()


# https://stackoverflow.com/questions/16586180/typeerror-objectid-is-not-json-serializable to deal with the circular reference error
class JSONEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, ObjectId):
            return str(o)
        return json.JSONEncoder.default(self, o)


preurl = "http://api.scraperapi.com?key=ba5ace7791ef9891c05e8947f45f6f11&url="

desktop_agents = [
    'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36',
    'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36',
Esempio n. 3
0
from chalice import Chalice
from chalicelib.s3_manager import S3ManagerCore
import logging
import json
import time

app = Chalice(app_name='imager')
app.debug = True
app.log.setLevel(logging.DEBUG)


@app.on_sqs_message(queue='imager-queue', batch_size=1)
def build(event):
    #app.log.info("Event: %s", event.to_dict())
    event = event.to_dict()
    status_code = 200
    records = event.get('Records', None)
    try:
        if records is not None and records:
            for rec in records:
                print(rec)
                try:
                    body = json.loads(rec['body'])
                    domain_id = body.get('domain_id')
                    filename = body.get('filename')
                    url = body.get('url')
                    build_core(domain_id, filename, url)
                except Exception as e:
                    app.log.error(e)
    except Exception as e:
        status_code = 400
Esempio n. 4
0
from chalice import Chalice
import boto3

app = Chalice(app_name='helloworld')

# Get the service resource.
dynamodb = boto3.resource('dynamodb')

# Instantiate a table resource object without actually
# creating a DynamoDB table. Note that the attributes of this table
# are lazy-loaded: a request is not made nor are the attribute
# values populated until the attributes
# on the table resource are accessed or its load() method is called.
table = dynamodb.Table('users')


@app.route('/')
def index(key={'username': '******', 'last_name': 'Doe'}):
    response = table.get_item(Key=key)
    item = response['Item']
    return item


# 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"}
Esempio n. 5
0
from chalice import Chalice, Response
from enum import Enum
from botocore.vendored import requests

app = Chalice(app_name='alfred_server')
app.debug = True


@app.route('/')
def index():
    return {'status': 'healthy'}


@app.route('/process/message', methods=['POST'])
def process_message():
    alfred = Alfred()
    request_body = app.current_request.json_body
    input_message_type = request_body[
        "type"]  #Message has to have a type matching MessageType enum
    handler_urls = alfred.handlers[input_message_type.upper()]
    for handler_url in handler_urls:
        # Process message by each handler
        send_message_to_handler(handler_url, request_body)
    response_body = {"body": request_body, "handler_urls": handler_urls}
    return Response(body=response_body)


def send_message_to_handler(handler_url, message):
    response = requests.post(handler_url, message)
    return response
Esempio n. 6
0
import boto3
from chalice import Chalice, Cron
from github import Github
from lxml import html
from pytz import timezone
import pytz
import requests

s3_client = boto3.client('s3')
textract_client = boto3.client('textract')

BUCKET_NAME = 'foodscrapes'
REPO_NAME = 'spulec/foodscrapes'

app = Chalice(app_name="foodscrapes")


@app.schedule(Cron(0, 20, '*', '*', '?', '*'))
def main(event):
    res = requests.get("https://www.thomaskeller.com/tfl/menu")
    root = html.fromstring(res.content)
    menu_link = root.xpath("//a[contains(@type, 'pdf')]")[0].attrib['href']
    file_name = menu_link.split("/")[-1]
    menu_res = requests.get(menu_link)
    s3_client.put_object(
        Body=menu_res.content,
        Bucket=BUCKET_NAME,
        Key=file_name,
    )
Esempio n. 7
0
    os.environ["BUCKET_PREFIX"] = "local-grapl"
else:
    JWT_SECRET_ID = os.environ["JWT_SECRET_ID"]

    client = boto3.client("secretsmanager")

    JWT_SECRET = client.get_secret_value(
        SecretId=JWT_SECRET_ID, )["SecretString"]

ORIGIN = os.environ["UX_BUCKET_URL"].lower()

ORIGIN_OVERRIDE = os.environ.get("ORIGIN_OVERRIDE", None)

LOGGER.debug("Origin: %s", ORIGIN)
app = Chalice(app_name="model-plugin-deployer")


def into_list(t: Union[T, List[T]]) -> List[T]:
    if isinstance(t, list):
        return t
    return [t]


def check_jwt(headers):
    encoded_jwt = None
    for cookie in headers.get("Cookie", "").split(";"):
        if "grapl_jwt=" in cookie:
            encoded_jwt = cookie.split("grapl_jwt=")[1].strip()

    if not encoded_jwt:
Esempio n. 8
0
from chalice import Chalice, CORSConfig
from PIL import Image
from io import BytesIO
import boto3
import cgi
import random
import string
import time

app = Chalice(app_name='imageupload')
app.api.binary_types.append('multipart/form-data')
cors_config = CORSConfig(allow_origin="*", allow_headers=["Content-Type"])

_ALLOWED_ORIGINS = set(
    ["https://www.paytime.co.kr", "http://test.paytime.co.kr"])


@app.route('/')
def index():
    return {'hello': 'world'}


def _get_parts(file_field="file"):
    request_body = app.current_request._body
    body = app.current_request.raw_body

    content_type_header = app.current_request.headers['content-type']
    content_type, property_dict = cgi.parse_header(content_type_header)

    property_dict['boundary'] = bytes(property_dict['boundary'], "utf-8")
    form_data = cgi.parse_multipart(BytesIO(body), property_dict)
Esempio n. 9
0
from chalice import Chalice
import boto3
import json

app = Chalice(app_name='GOTOams Bot')
app.debug = True
lex = boto3.client('lex-runtime', region_name='us-east-1')


@app.route('/', methods=['POST'])
def index():
    body = app.current_request.json_body
    response = lex.post_text(botName='GOTOams Bot',
                             botAlias='GOTOams Bot',
                             userId='sampleuserid',
                             inputText=body['usertext'])
    return response


@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.json_body
#     # Suppose we had some 'db' object that we used to
#     # read/write from our database.
Esempio n. 10
0
#     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.
#

import os
import logging
import boto3
import botocore
from chalice import Chalice, AuthResponse
from chalicelib import auth, db
from boto3.dynamodb.types import Binary

app = Chalice(app_name='swiperapp')
app.debug = True
_DB = None
_USER_DB = None
log = logging.getLogger('log-demo')
log.setLevel(logging.DEBUG)


@app.route('/register', methods=['POST'])
def create_user():
    body = app.current_request.json_body
    warning_messages = []
    try:
        body['email']
        if len(body['email']) > 200:
            warning_messages.append('Email is too long.')
Esempio n. 11
0
from __future__ import print_function # Python 2/3 compatibility
from chalice import Chalice
import boto3
import json
import decimal
from boto3.dynamodb.conditions import Key, Attr
from botocore.exceptions import ClientError

app = Chalice(app_name='books')
#dynamodb = boto3.resource("dynamodb", region_name='us-west-2', endpoint_url="http://*****:*****@app.route('/books', methods=['GET'], api_key_required=True, cors=True)
def books_index():
    table = dynamodb.Table('Books')
    try:
        response = table.scan(
        )
    except ClientError as e:
        print(e.response['Error']['Message'])
    else:
        return response["Items"]
    

@app.route('/books/{id}', methods=['GET'], api_key_required=True, cors=True)
def find_book(id):
    table = dynamodb.Table('Books')
    print("id sent: " + id)
    try:
        response = table.get_item(
            Key={
Esempio n. 12
0
from chalice import Chalice, Response
from chalicelib.middleman import do_milb
import icalendar

app = Chalice(app_name='icsMiddleman')


@app.route('/')
def index():
    return {'hello': 'world'}

@app.route('/milb/{teamtoken}')
def get_milb(teamtoken):
	return Response(body=do_milb(teamtoken),
		status_code=200,
		headers={'Content-Type': 'text/calendar'})
Esempio n. 13
0
from chalice import Chalice
import logging
import json
import random
import re
import os
import sys
import utils

app = Chalice(app_name='alexa-launchmens')
logger = logging.getLogger()
debug = os.environ.get('DEBUG_MODE')
if debug == '1':
    logger.setLevel(logging.INFO)
else:
    logger.setLevel(logging.ERROR)

#mp3
drumrole_mp3 = "soundbank://soundlibrary/musical/amzn_sfx_drum_and_cymbal_01"


@app.lambda_function()
def lambda_handler(event, context):
    request = event['request']
    request_type = request['type']
    session = {}

    if request_type == 'LaunchRequest':
        return questionIntent()
    elif request_type == 'IntentRequest' and 'intent' in request:
        if 'dialogState' in request and request['dialogState'] != 'COMPLETED':
Esempio n. 14
0
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)
    :license: MIT, see LICENSE for more details.
"""

import uuid
import json
import boto3
import base64
import logging
from chalicelib import cognito
from chalicelib.config import cors_config
from chalicelib.util import pp, save_s3_chalice, get_parts, delete_s3
from chalicelib.model_ddb import Photo, create_photo_info, ModelEncoder, with_presigned_url
from chalice import Chalice, Response, ConflictError, BadRequestError, AuthResponse, ChaliceViewError
from botocore.exceptions import ParamValidationError

app = Chalice(app_name='cloudalbum')
app.debug = True
app.log.setLevel(logging.DEBUG)


@app.authorizer()
def jwt_auth(auth_request):
    """
    JWT based authorizer
    :param auth_request:
    :return: AuthResponse
    """
    token = auth_request.token
    try:
        decoded = cognito.token_decoder(token)
        return AuthResponse(routes=['*'], principal_id=decoded['sub'])
Esempio n. 16
0
from chalice import Chalice
from chalice import BadRequestError
import base64, os, boto3, ast
import numpy as np
import os
import cv2
from PIL import Image
import requests
import boto3
import h5py
import json
from io import BytesIO

app = Chalice(app_name='chalice')
app.debug = True

s3 = boto3.resource('s3')
bucket = s3.Bucket('test-bucket')
file_name = 's3://malariaimages498/cell_images/Parasitized/C100P61ThinF_IMG_20150918_144104_cell_168.png'
endpoint_name = 'sagemaker-tensorflow-2019-04-13-16-22-06-941'
#s3://sagemaker-us-east-1-554240446913/model/model.tar.gz
#s3://sagemaker-us-east-1-554240446913/model/test_X.h5

#h5f = h5py.File('s3://sagemaker-us-east-1-554240446913/model/test_X.h5','r')
s3client = boto3.client('s3')  #low-level functional API
resource = boto3.resource('s3')  #high-level object-oriented API
my_bucket = resource.Bucket('sagemaker-us-east-1-554240446913'
                            )  #subsitute this for your s3 bucket name.
obj = s3client.get_object(Bucket='sagemaker-us-east-1-554240446913',
                          Key='model/test_X.h5')
h5f = h5py.File(BytesIO(obj['Body'].read()))
Esempio n. 17
0
import requests, json
from chalice import Chalice

app = Chalice(app_name='webhook-alert')  # Creates Chalice instance

API_KEY = 'YOUR-API-KEY'  # Alpaca account API key
SECRET_KEY = 'YOUR-SECRET-API-KEY'  # Alpaca account secret key
BASE_URL = "https://paper-api.alpaca.markets"  # Alpaca URL
ORDERS_URL = "{}/v2/orders".format(BASE_URL)  # Routes to Alpaca order URL
HEADERS = {
    'APCA-API-KEY-ID': API_KEY,
    'APCA-API-SECRET-KEY': SECRET_KEY
}  # Header parameters


@app.route('/buy_stock',
           methods=['POST'])  # Buy stock route that sends and recieves data
def buy_stock():  # Defines buy stock page
    webhook - request = app.current_request  # Gets webhook alert as JSON message
    webhook - alert = request.json_body  # Translates webhook alert to dictionary

    data = {  # Initializes data dictionary
        "symbol": webhook - alert['ticker'],  # Gets symbol of webhook alert
        "qty": 1,  # Sets quantity to 1 stock
        "side": "buy",  # Buy parameter
        "type": "limit",
        "limit_price": webhook - alert['close'],
        "time_in_force": "gtc",
        "order_class": "bracket",
        "take_profit": {
            "limit_price": webhook -
Esempio n. 18
0
import json
import logging
import random
import os
import uuid
import subprocess
import csv
import math

import boto3
import subprocess
import urllib.parse
from chalice import Chalice, Response
import markovify

app = Chalice(app_name='multi-armed-bandit')
app.log.setLevel(logging.INFO)

EPSILON = 0.15

FROM = 0
TO = 1
FACTOR = 1000

es_file = os.path.join(os.path.dirname(__file__), 'chalicelib',
                       'boleros_es.txt')
en_file = os.path.join(os.path.dirname(__file__), 'chalicelib',
                       'boleros_en.txt')

with open(es_file) as f:
    text = f.read()
Esempio n. 19
0
import boto3
import os
import uuid
from chalice import Chalice
from chalice import BadRequestError, NotFoundError

app = Chalice(app_name='dad-jokes')
app.debug = True
client = boto3.client('dynamodb')


@app.route('/', cors=True)
def index():
    response = client.scan(TableName=os.environ['APP_TABLE_NAME'], Limit=10)

    return response


@app.route('/joke', methods=['POST'], cors=True)
def add_joke():
    joke = app.current_request.json_body.get('joke', '')
    punchline = app.current_request.json_body.get('punchline', '')

    if not joke or not punchline:
        raise BadRequestError(
            "You must provide an object with keys of 'joke' and 'punchline'")
    joke_uuid = str(uuid.uuid4())
    response = client.put_item(TableName=os.environ['APP_TABLE_NAME'],
                               Item={
                                   'uuid': {
                                       'S': joke_uuid
Esempio n. 20
0
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):
Esempio n. 21
0
from chalice import Chalice, Response

#
import pokemon
import json
from urllib.parse import parse_qs

app = Chalice(app_name='pokegram')
app.debug = True


@app.route('/favicon.ico')
def favicon():
    '''
    This is only to return the favicon.ico file that is required when running chalice locally
    '''
    return Response(body="favicon",
                    headers={"Content-Type": "text/plain"},
                    status_code=200)


@app.route('/api/health')
def health():
    '''
    The root path return a text message of "API OK"
    '''
    return Response(body="API OK",
                    headers={"Content-Type": "text/plain"},
                    status_code=200)

Esempio n. 22
0
from chalice import Chalice
from datetime import datetime
import requests
from chalicelib import API_KEY

app = Chalice(app_name='hellochalice')


@app.route('/')
def index():
    return {'hello': 'world'}


@app.route('/time')
def gettime():
    now = datetime.now()
    current_time = now.strftime("%D %H:%M:%S")
    return f"The time is {current_time}"


@app.route('/echo', methods=['POST'])
def echoback():
    request = app.current_request
    message = request.json_body
    return message


@app.route('/price/{symbol}')
def index(symbol):
    symbol = symbol.upper()
    url = f"https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest?symbol={symbol}"
Esempio n. 23
0
import boto3
from boto3.dynamodb.conditions import Key, Attr
from chalice import Chalice
import json
import os
import unittest


app = Chalice(app_name='BoardMicroservice')
app.debug=os.getenv('DEBUG', True)

aws_account_id = boto3.client('sts').get_caller_identity().get('Account')
region = os.getenv('region','us-east-1')
topic_vehiclemoved = os.getenv('topic_vehiclemoved', 'vehicle_moved')
sns_base = 'arn:aws:sns:us-east-1:'
topic_unlock_arn = sns_base + aws_account_id + os.getenv('topic_unlock', ':vehicle_unlock')
topic_round_arn = sns_base + aws_account_id + os.getenv('topic_round', ':round_reset')
move_arn = sns_base + aws_account_id + os.getenv('topic_move', ':moves_to_process')
vehicles = int(os.getenv('vehicles', 4))

iot_table = os.getenv('iot_game_table', 'iot_racer')

dynamodb_table = boto3.resource('dynamodb', region_name=region).Table(iot_table)
iot_dp = boto3.client('iot-data', region_name=region)
sns = boto3.client('sns', region_name=region)

@app.route('/joysticks/{vehicle}/{move}', methods=['POST'])
def vehicle_move(vehicle, move):
    message = {}
    message['joystick']=vehicle
    message['move']=move
Esempio n. 24
0
from chalice import Chalice
from chalice import BadRequestError
import base64, os, boto3, ast
import numpy as np

app = Chalice(app_name='predictor')
app.debug = True


@app.route('/', methods=['POST'])
def index():
    body = app.current_request.json_body

    if 'data' not in body:
        raise BadRequestError('Missing data')
    if 'ENDPOINT_NAME' not in os.environ:
        raise BadRequestError('Missing endpoint')

    image = base64.b64decode(body['data'])  # byte array
    endpoint = os.environ['ENDPOINT_NAME']

    if 'topk' not in body:
        topk = 257
    else:
        topk = body['topk']

    print("%s %d" % (endpoint, topk))

    runtime = boto3.Session().client(service_name='sagemaker-runtime',
                                     region_name='us-east-1')
    response = runtime.invoke_endpoint(EndpointName=endpoint,
Esempio n. 25
0
        ps = PolygonStruct(vertexlist)
        ps.setInitialVertex()

        while not ps.allPointsUsed():
            ps.cycle()
            if ps.stuck:
                break
            if ps.checkValidFinalPolygon():
                ps.lov.append(ps.initialvertex)
                results.append(ps.getJSON())

                break
    return results


app = Chalice(app_name='polygon')
app.debug = True


@app.route('/polygon/{vertexlist}')
def vertexlist(vertexlist):
    even = vertexlist.split(",")[0::2]
    odd = vertexlist.split(",")[1::2]

    vl = [(int(i), int(j)) for i, j in zip(even, odd)]

    return {'result': generate(vl)}


if __name__ == "__main__":
    vertexlist = sys.argv[1]
Esempio n. 26
0
import os
import boto3
import gitlab
import logging
import traceback

from botocore.client import BaseClient
from typing import Any, Dict, Iterable, Text, Tuple
from chalice import Chalice, ForbiddenError, BadRequestError
from gitlab.v4.objects import (
    Project, ProjectBranch, ProjectMergeRequest, ProjectLabel)


app = Chalice(app_name='mailmania')
app.log.setLevel(logging.DEBUG)

BACKPORT_DESTINATION = os.getenv('BACKPORT_BRANCH', 'release-3.1')

gl = gitlab.Gitlab('https://gitlab.com',
                   os.getenv('GITLAB_TOKEN'), api_version=4)

ses = None


class BackportFailedError(Exception):
    pass


def prepare_email(subject: Text, body: Text) -> Dict['str', object]:
    email = {
        'Subject': {
Esempio n. 27
0
from chalice import Chalice, Response
import uuid
import time
import boto3

app = Chalice(app_name='backend')
app.debug = True

USE_DYNAMO = True


@app.route('/')
def index():
    return {'hello': 'world'}


POSTS = [{
    'id': '6d503941-8d24-437c-9f19-88c0c6dce48b',
    'title': 'Complaints at Fosenkoia',
    'content':
    "We have received some complaints from neighbours at Fosen. Don't walk through private gardens! When walking from the speed boat you need to go up to the main road behind the store. The road along the docks is a dead end and will lead you into private gardens.",
    'status': 'ACTIVE',
    'timestamp': int(time.time())
}, {
    'id': '5e7995cb-7422-4b2d-a5ed-8907a3bbe435',
    'title': 'Summer Reservation Period',
    'content':
    "The summer reservation period starts may 30th. From that date on you can reserve cabins between june 8th and 23rd august. Akademika is not open all summer, so remember to check their opening hours so you can pick up keys.",
    'status': 'ACTIVE',
    'timestamp': int(time.time())
}]
 * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'''
import logging
import os
import json
import util
import s3_handler
import ddb_handler

from chalice import Chalice, BadRequestError, NotFoundError
from chalice import CognitoUserPoolAuthorizer

app = Chalice(app_name='source-of-truth-api')
app.debug = True

logging.basicConfig()
logging.getLogger().setLevel(logging.INFO)

authorizer = CognitoUserPoolAuthorizer(
    'SourceOfTruthUserPool', provider_arns=[os.environ['COGNITO_USER_POOL']])

@app.route('/upload', methods=['POST'], content_types=['application/json'], authorizer=authorizer, cors=True)
def upload_s3_file():
    request_body = json.loads(app.current_request.raw_body)
    return ddb_handler.handle_upload_file_req(request_body, app.current_request.context)

@app.route('/download', methods=['POST'], content_types=['application/json'], authorizer=authorizer, cors=True)
def download_s3_file():
Esempio n. 29
0
from botocore.exceptions import ClientError
from chalice import Chalice, CORSConfig, NotFoundError, BadRequestError, Response, AuthResponse, AuthRoute, \
    CognitoUserPoolAuthorizer
from basicauth import decode
import logging
import boto3
from hashlib import blake2b
import json

app = Chalice(app_name='serverlessbackend')

app.log.setLevel(logging.DEBUG)

cors_config = CORSConfig(allow_origin="*")

users_video_dictionary = {"*****@*****.**": []}


@app.route('/')
def index():
    return {'hello': 'world'}


@app.authorizer()
def basic_auth(auth_request):
    username, password = decode(auth_request.token)

    if username == password:
        context = {'is_admin': True}
        return AuthResponse(routes=[AuthRoute('/*', ["GET", "POST"])],
                            principal_id=username,
Esempio n. 30
0
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
Esempio n. 31
0
"""

import os
import time

import boto3
from chalice import Chalice, Rate

from chalicelib import cache
import chalicelib.channels as channel_tiles
import chalicelib.cloudwatch as cloudwatch_data
import chalicelib.layout as node_layout
import chalicelib.periodic as periodic_handlers
import chalicelib.settings as msam_settings

app = Chalice(app_name='msam')

# update as many regions possible at this interval
NODE_UPDATE_RATE_MINUTES = 5

# update one region at this interval
SSM_NODE_UPDATE_RATE_MINUTES = 5

# update connections at this interval
CONNECTION_UPDATE_RATE_MINUTES = 5

# update MSAM visuals from tags at this interval
TAG_UPDATE_RATE_MINUTES = 5

# update managed instance status and metrics at this interval
SSM_RUN_COMMAND_RATE_MINUTES = 1
Esempio n. 32
0
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())))
Esempio n. 33
0
from chalicelib import keys
from twilio.rest import Client
import sys
import logging
import pymysql
import secrets
from passlib.hash import pbkdf2_sha256
import string
import random
import datetime
from google.transit import gtfs_realtime_pb2
import requests
from protobuf_to_dict import protobuf_to_dict
import googlemaps

app = Chalice(app_name="RunningLateTest")
app.debug = True


def get_date_time(plus_hours=0):
    return (datetime.datetime.now() +
            datetime.timedelta(hours=plus_hours)).strftime('%Y-%m-%d %H:%M:%S')


def get_date_string(timestamp):
    time_format = '%Y-%m-%d %H:%M:%S'
    return datetime.datetime.strptime(timestamp, time_format)


def get_connection():
    rds_host = keys.rds_host