def presigned_url(project, step):
    if app.current_request.query_params is None:
        raise NotFoundError("No parameter has been sent")

    mail = app.current_request.query_params.get('mail')
    if len(mail) == 0:
        raise NotFoundError("mail is empty")
    print("query_param mail: " + mail)

    if project is None or len(project) == 0:
        raise NotFoundError("project is empty")
    print("query_param project: " + project)

    step_number = 0
    if step is not None or len(step) > 0:
        try:
            step_number = int(step)
        except ValueError:
            print("query_param v is not a number: " + step)
            step_number = 0
    print("query_param step: " + step)

    h = blake2b(digest_size=10)
    byte_mail = bytes(mail, 'utf-8')
    h.update(byte_mail)
    hexmail = h.hexdigest()
    print("hex mail: " + hexmail)

    new_user_video = project + "/" + str(step_number) + "/" + hexmail + '.webm'
    if check_if_file_exists(new_user_video):
        return Response(body="The resource you requested does already exist",
                        status_code=403,
                        headers={'Content-Type': 'text/plain'})

    try:
        get_dynamodb_table().put_item(
            Item={
                "ProjectStep": project + "-" + str(step_number),
                "Mail": mail,
                "video": new_user_video
            })
    except Exception as e:
        print(e)
        raise NotFoundError("Error adding an element on dynamodb")

    try:
        response = get_s3_client().generate_presigned_post(
            Bucket=MEDIA_BUCKET_NAME,
            Key=new_user_video,
            Fields={"acl": "public-read"},
            Conditions=[{
                'acl': 'public-read'
            }],
            ExpiresIn=3600)
    except ClientError as e:
        logging.error(e)
        raise BadRequestError("Internal Error generating presigned post ")
    return response
Esempio n. 2
0
def get_availability(service_name):
    if not VALID_NAME.match(service_name):
        return INVALID_RESPONSE
    service_name_no_suffix = _remove_suffix(service_name)

    row = dynamodb.get_item(
        TableName='application_statuses',
        Key={'service_name': {
            'S': service_name_no_suffix
        }})

    availability = None
    badge_color = 'lightgrey'
    availability_str = _recursive_get(row, 'Item', 'availability', 'N')
    if availability_str:
        availability = float(availability_str)
        badge_color = 'brightgreen' if availability >= 99.999 else 'yellow' if availability >= 95.0 else 'red'

    headers = {
        'Cache-Control': 'no-cache, no-store, max-age=0, must-revalidate',
        'Access-Control-Allow-Origin': '*'
    }

    if service_name.endswith('.svg'):
        headers['Content-Type'] = 'image/svg+xml'
        svg = make_availability_svg(badge_color, availability)
        return Response(status_code=200,
                        headers={
                            'Content-Type':
                            'image/svg+xml',
                            'Cache-Control':
                            'no-cache, no-store, max-age=0, must-revalidate'
                        },
                        body=svg)

    if not availability:
        return Response(status_code=404,
                        body=dict(service_name=service_name_no_suffix,
                                  status="not found"))

    headers['Content-Type'] = 'application/json'
    return Response(status_code=200,
                    headers=headers,
                    body=dict(service_name=service_name_no_suffix,
                              availability=availability))
Esempio n. 3
0
def handleUpdateProject(project, body):
    # user should not include a projectName, especially different one from project!
    if 'projectName' in body:
        if body['projectName'] != project:
            return Response(body={'Error': 'A projectName cannot be changed'},
                            status_code=403)
        else:
            del body['projectName']
    # check if the project has valid properties / values
    valProject = validateProject(body, False)
    if 'Error' in valProject: return Response(body=valProject, status_code=400)
    # if there are no keys left in project, reject request
    if len(valProject) < 1:
        return Response(body={'Error': 'Request must include a valid update'},
                        status_code=400)
    valProject = makeLowLevelDict(valProject)
    # set up some storage to help with the dynamoDB operation
    updates = []
    expAttValues = {':projectName': {'S': project}}
    # form update expression for dynamoDB operation
    updateExpr = 'SET '
    for key in valProject:
        updates.append(key + ' = :' + key)
        expAttValues[':' + key] = valProject[key]
    updateExpr += (', ').join(updates)
    # get data from dynamoDB
    try:
        response = client.update_item(
            TableName='projects',
            Key={'projectName': {
                'S': project
            }},
            ReturnValues='UPDATED_NEW',
            ReturnConsumedCapacity='NONE',
            ReturnItemCollectionMetrics='SIZE',
            UpdateExpression=updateExpr,
            ConditionExpression='projectName = :projectName',
            ExpressionAttributeValues=expAttValues)
    except:
        return Response(body={'Error': 'Requested node does not exist'},
                        status_code=404)
    # deserialize the dynamoDB results to simplify for the user
    if 'Attributes' in response:
        response['Attributes'] = makeNormalDict(response['Attributes'])
    return response
Esempio n. 4
0
def findsubproject(projectid, subprojectid):
    res = dynamoHelper.get_single_sub_doc(dynamo_subproject_table_name,
                                          projectid, subprojectid)
    return Response(body={
        'response': 'Successfully returned response',
        'message': res
    },
                    status_code=200,
                    headers={'Content-Type': 'application/json'})
Esempio n. 5
0
def do_auth_and_return(ctxt):

    log.debug('context: {}'.format(ctxt))
    here = ctxt['path']
    log.info("here will be {0}".format(here))
    redirect_here = quote_plus(here)
    URS_URL = get_urs_url(ctxt, redirect_here)
    log.info("Redirecting for auth: {0}".format(URS_URL))
    return Response(body='', status_code=302, headers={'Location': URS_URL})
Esempio n. 6
0
def post_fail():
    return Response(
        status_code=400,
        body={
            'status': 400,
            'payload': 'Contact could not be inserted.'
        },
        headers=response_headers
    )
Esempio n. 7
0
def successful():
    return Response(
        status_code=201,
        body={
            'status': 201,
            'payload':
            "Payment and campaign creation process completed correctly"
        },
        headers=response_headers)
Esempio n. 8
0
def add_user():
    body = app.current_request.json_body
    db_client = connect__mongodb()
    if len(body["username"]) <= 0:
        # 400 Error Response
        return Response(body='No username was provided',
                        status_code=400,
                        headers={'Content-Type': 'text/plain'})
    matching_users = db_client["users"].find_one(
        {"username": body["username"]})
    if matching_users is not None:
        # 400 Error Response
        return Response(body='Username is already in use',
                        status_code=400,
                        headers={'Content-Type': 'text/plain'})
    body["_id"] = str(generate_uuid())
    db_client["users"].insert_one(body)
    return {"res": body}
Esempio n. 9
0
def get_success(response):
    return Response(
        status_code=200,
        body={
            'status': 200,
            'payload': response
        },
        headers=response_headers
    )
Esempio n. 10
0
def predict(complaint_type: str) -> Response:

    if complaint_type in model:
        return Response(status_code=200,
                        headers={'Content-Type': 'application/json'},
                        body={
                            'status': 'success',
                            'complaint_type': complaint_type,
                            'estimated_time': model[complaint_type]
                        })
    else:
        return Response(status_code=400,
                        headers={'Content-Type': 'application/json'},
                        body={
                            'status': 'failure',
                            'complaint_type': complaint_type,
                            'estimated_time': model['overal_median']
                        })
Esempio n. 11
0
def calling_create_crawler():
    dbName = "yash-quickstart-datalake-raw-bucket-db"
    s3path = "s3://yash-quickstart-datalake-raw-us-west-2/"
    crawName = "yash-quickstart-datalake-raw-bucket-crawler"
    region = "us-west-2"
    endpoint = "https://glue.us-west-2.amazonaws.com"

    try:

        crawler_name = createcrawler(dbName, s3path, crawName, region,
                                     endpoint)
        return Response(body=crawler_name,
                        status_code=200,
                        headers={'Content-Type': 'text/plain'})
    except Ecxeption as e:
        return Response(body={"Lambda Call Failed because of:": e},
                        status_code=500,
                        headers={'Content-Type': 'text/plain'})
Esempio n. 12
0
def manager_call():
    """ display the complaints data
    """
    process.reset_content()
    
    mydict = {}
    t = j2_env.get_template('reset.html')
    
    return Response(body=t.render(my_dict=mydict), status_code=200, headers={'Content-Type': 'text/html'})
def render_to_response(template_path, **context):
    return Response(
        render_template(template_path, **context),
        status_code=200,
        headers={
            "Content-Type": "text/html",
            "Access-Control-Allow-Origin": "*"
        },
    )
Esempio n. 14
0
def delete_task(task_id):
    try:
        deleted_task_ids = task.delete_tasks(g.current_user, (int(task_id), ))
        return Response(body={'deleted': deleted_task_ids}, status_code=200)
    except DeletionError as error:
        raise APIError(
            status=404,
            detail=f'task with id {error} can not be deleted: '
            'no such task id or the task does not belong to the user')
 def _compress_response(*args, **kwargs):
     data = view(*args, **kwargs)
     blob = json.dumps(data).encode("utf-8")
     payload = gzip.compress(blob)
     custom_headers = {
         "Content-Type": "application/json",
         "Content-Encoding": "gzip",
     }
     return Response(body=payload, status_code=200, headers=custom_headers)
Esempio n. 16
0
def add_volunteer():
    request = app.current_request
    body = request.json_body
    flag = database.insert_volunteer(body)
    if flag:
        return Response(
            status_code=200,
            body={
                'message': f'Voluntario \"{body["name"]} {body["midname"]}\" inserido com sucesso!'
            }
        )
    return Response(
            status_code=400,
            body={
                'message': f'Nao foi possivel inserir o usuario no sistema!\n'
                           f'Verifique se as informacoes foram passadas corretamente'
            }
        )
Esempio n. 17
0
def healthcheck() -> Response:
    """
    A simple endpoint to perform system healthcheck

    :return: Chalice response object.
    """
    # log request and return
    log(app.current_request.to_dict(), app.current_request.json_body)
    return Response(status_code=200, body={"message": "I am healthy."})
Esempio n. 18
0
def add_action():
    request = app.current_request
    body = request.json_body
    flag = database.insert_actions(body)
    if flag:
        return Response(
            status_code=200,
            body={
                'message': f'Acao \"{body["name"]} - {body["institution"]}\" inserida com sucesso!'
            }
        )
    return Response(
        status_code=400,
        body={
            'message': f'Nao foi possivel inserir a acao no sistema!\n'
                       f'Verifique se as informacoes foram passadas corretamente'
        }
    )
Esempio n. 19
0
def get_spooked(conn):
    try:
        with conn.cursor() as cursor:
            query = "SELECT * FROM PlaceUser ORDER BY RAND() LIMIT 1"
            cursor.execute(query)
            result = cursor.fetchone()
            return Response(result)
    finally:
        conn.close()
Esempio n. 20
0
def create_item():
    event = app.current_request.json_body
    try:
        input_item: Item = Item.Schema().load(data=event)
    except ValidationError as err:
        print(err.messages)
        raise BadRequestError(err.messages)
    get_items_db().add_item(input_item)
    return Response(body="", status_code=201)
def api_info(validated_body):
    response_schema = models.Echo()
    response = json.dumps(response_schema.dump(validated_body))

    # Write the Response to Kinesis?
    events.record_event(response)

    # Return response for the consumer
    return Response(body=response, headers=headers, status_code=200)
Esempio n. 22
0
    def _convert_response(resp):
        if type(resp) is tuple:
            if len(resp) == 2:
                if type(resp[1]) is int:
                    return Response(body=resp[0], status_code=resp[1])
                elif type(resp[1]) is dict:
                    return Response(body=resp[0],
                                    status_code=200,
                                    headers=resp[1])
                else:
                    return Response(body="Internal error (wrong result type)",
                                    status_code=500)
            else:
                return Response(body=resp[0],
                                status_code=resp[1],
                                headers=resp[2])

        return resp
Esempio n. 23
0
def request_password_reset():
    body = blueprint.current_request.json_body

    try:
        password_reset_details = PasswordResetRequestDetails().load(body)
        auth.request_password_reset(password_reset_details['email'])
        return Response(body={}, status_code=200)
    except auth.UserNotFound:
        raise APIError(status=404, detail='User not found')
Esempio n. 24
0
def custom_response():
    return Response(
        status_code=204,
        body='',
        headers={
            'Content-Type': 'text/plain',
            'Set-Cookie': ['key=value', 'foo=bar'],
        },
    )
Esempio n. 25
0
def login():
    status_code, template_vars, headers = do_login(
        app.current_request.query_params, app.current_request.context,
        os.getenv('COOKIE_DOMAIN', ''))
    if status_code == 301:
        return Response(body='', status_code=status_code, headers=headers)

    return make_html_response(template_vars, headers, status_code,
                              'error.html')
Esempio n. 26
0
def read(collection, label, column):
    collection = unquote(collection).strip()
    label = unquote(label).strip()
    column = unquote(column).strip()
    params = app.current_request.query_params or {}

    series = repo / collection / label
    start = params.pop("ui.start", None)
    stop = params.pop("ui.stop", None)

    # find time dimension
    tdim = None
    for name, coldef in series.schema.idx.items():
        if coldef.codec.dt == 'datetime64[s]':
            tdim = name
            break
    else:
        # No time dimension found
        return

    # Query series
    page = int(params.get('ui.page', '0'))
    offset = page * PAGE_LEN
    extra_cols = tuple(col for col, value in params.items() if value)
    cols = (tdim, column) + extra_cols
    cols = (tdim, column) + extra_cols
    frm = series.frame(limit=PAGE_LEN,
                       offset=offset,
                       start=start,
                       stop=stop,
                       select=cols)

    # Slice other columns
    for col, value in params.items():
        if col not in frm.columns or not value:
            continue
        frm = frm.mask(frm[col] == value)  # FIXME

    # Aggregate on time dimension
    if len(series.schema.idx) > 1:
        agg_col = f'(sum self.{column})'
        frm = frm.reduce(tdim, agg_col)
        data = [frm[tdim].astype(int), frm[agg_col]]
    else:
        data = [frm[tdim].astype(int), frm[column]]

    # Build response
    content = orjson.dumps(
        {
            'data': data,
            'options': uplot_options
        },
        option=orjson.OPT_SERIALIZE_NUMPY,
    )
    payload = gzip.compress(content, compresslevel=1)
    headers = {'Content-Type': 'application/json', 'Content-Encoding': 'gzip'}
    return Response(body=payload, status_code=200, headers=headers)
Esempio n. 27
0
def post_success(uid):
    return Response(
        status_code=201,
        body={
            'status': 201,
            'payload': uid
        },
        headers=response_headers
    )
Esempio n. 28
0
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,
        )
Esempio n. 29
0
def youtube():
    status_code, result, how = do_search_on_youtube(
        app.current_request.query_params)
    if status_code == requests.codes.ok:
        return result
    else:
        return Response(body=json.dumps(result),
                        status_code=status_code,
                        headers={"Content-Type": "application/json"})
Esempio n. 30
0
def index():
    with open('./chalicelib/template.html', 'r') as f:
        template = f.read()
    return Response(template,
                    status_code=200,
                    headers={
                        "Content-Type": "text/html",
                        "Access-Control-Allow-Origin": "*"
                    })