def get_purchase_orders_by_ship_date(event, context): """ Get list of purchase orders by ship_date range """ logger.debug('event: {}'.format(event)) params = get_path_parameters(event) min_ship_date = params['min_ship_date'] max_ship_date = params.get('max_ship_date', None) if hasattr(context, 'supplier_id'): supplier_id = context.supplier_id distributors = [] else: supplier_id = None distributor_id = context.distributor_id try: repo = DynamoRepository( region_name=os.environ['REGION'], dynamodb_local_endpoint=os.environ['DYNAMO_ENDPOINT']) except KeyError: repo = DynamoRepository(region_name=os.environ['REGION'], ) supplier_distributors = repo.get_all_distributor_suppliers( distributor_id) distributors = [ item['supplier_distributor_id'] for item in supplier_distributors ] items = context.repo.get_purchase_orders_by_ship_date_range( min_ship_date, max_ship_date, supplier_id, distributors) return {'statusCode': 200, 'body': json.dumps(items)}
def get_every_brand(event, context): """ Get all brands """ logger.debug('event: {}'.format(event)) if hasattr(context, 'supplier_id'): supplier = context.supplier_id else: distributor_id = context.distributor_id try: repo = DynamoRepository( region_name=os.environ['REGION'], dynamodb_local_endpoint=os.environ['DYNAMO_ENDPOINT'] ) except KeyError: repo = DynamoRepository( region_name=os.environ['REGION'], ) supplier_distributors = repo.get_all_distributor_suppliers(distributor_id) supplier = [item['supplier_id'] for item in supplier_distributors] items = context.repo.get_all_brands(supplier) return { 'statusCode': 200, 'body': json.dumps(items) }
def wrapper(event, context): logger.debug('event: {}'.format(event)) try: token_parts = event['headers']['Authorization'].split(' ') except KeyError: return { 'statusCode': 401, 'body': 'The resource you are trying to access is private. ' 'Please provide an Authorization token' } auth_token = token_parts[1] decoded = jwt_decode(auth_token, AUTH0_CLIENT_PUBLIC_KEY) if 'email' in decoded and 'sub' in decoded: context.email = decoded['email'] context.user_id = decoded['sub'][6:] # App metadata is inserted into context in insert_repo() else: return { 'statusCode': 401, 'body': 'invalid_token. ' 'The access token provided is expired, ' 'revoked, malformed, ' 'or invalid for other reasons' } return handler(event, context)
def get_all_users_in_supplier(event, context): """ Get all users under a supplier """ logger.debug('event: {}'.format(event)) try: items = context.repo.get_all_users_in_supplier(context.supplier_id) return {'statusCode': 200, 'body': json.dumps(items)} except NoSuchEntity as ex: return { 'statusCode': 404, 'body': json.dumps( {'error': '{RESOURCE} not found'.format(RESOURCE=str(ex))}) } except NotAnAdminUser: return { 'statusCode': 403, 'body': json.dumps({'error': "Forbidden. Admins only"}) } except: logger.log_uncaught_exception()
def delete_by_id(event, context): """ Delete supplier by entity_id and version """ logger.debug('event: {}'.format(event)) params = get_path_parameters(event) try: entity_id = params['entity_id'] if context.supplier_id != entity_id: return { 'statusCode': 403, 'body': json.dumps({ 'error': 'Forbidden. x-supplier-id header must match entity_id' }) } context.repo.delete_supplier_by_id(entity_id) return {'statusCode': 204} except NoSuchEntity: return { 'statusCode': 404, 'body': json.dumps({'error': 'Resource not found'}) } except NotAnAdminUser: return { 'statusCode': 403, 'body': json.dumps({'error': "Forbidden. Admins only"}) }
def add_count(event, context): """ Add count inventory record """ logger.debug('event: {}'.format(event)) try: body = get_body(event) except json.JSONDecodeError: return { 'statusCode': 400, 'body': json.dumps({'error': 'Bad parameter(s) in request'}) } body["supplier_id"] = context.supplier_id try: body = context.repo.save_count(body) return {'statusCode': 200, 'body': json.dumps(body)} except BadParameters: return { 'statusCode': 400, 'body': json.dumps({'error': 'Bad request. The request was Malformed'}) } except NoSuchEntity as ex: return { 'statusCode': 404, 'body': json.dumps({ 'error': '{RESOURCE} Resource not found'.format(RESOURCE=str(ex)) }) }
def get_count_sheet_by_id(event, context): """ Get an count record by its id """ logger.debug('event: {}'.format(event)) params = get_path_parameters(event) try: entity_id = params['entity_id'] item = context.repo.get_count_by_id(context.supplier_id, entity_id) count_sheet_string = count_sheet.generate(item) return { 'statusCode': 200, 'body': count_sheet_string, 'isBase64Encoded': True } except NoSuchEntity as ex: return { 'statusCode': 404, 'body': json.dumps({ 'error': '{RESOURCE} Resource not found'.format(RESOURCE=str(ex)) }) }
def main(args): dataset = Dataset(batch_size) class_num = dataset.class_num() image_batch, label_batch = dataset.get_train_batch() image_batch = tf.reshape(image_batch, [-1, image_size, image_size, 3]) glaph_ = Graph(batch_size, class_num) train_op = glaph_.inference(image_batch, label_batch) gpu_options = tf.GPUOptions( per_process_gpu_memory_fraction=gpu_memory_fraction) sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False)) sess.run(tf.global_variables_initializer()) sess.run(tf.local_variables_initializer()) # with sess.as_default(): # sess.run(iterator.initializer) for epoch in range(epoch_num): i_batch, l_batch = sess.run([image_batch, label_batch]) # logger.debug('i_batch: %s, l_batch: %s' % (i_batch, l_batch)) _, loss_t, loss_p_adv, loss_p, los_re = sess.run(train_op) logger.debug('loss_t: %s, loss_p_adv: %s, loss_p: %s, los_re: %s' % (loss_t, loss_p_adv, loss_p, los_re)) sess.close()
def delete_user_in_supplier(event, context): """ Delete user in supplier by email_id """ logger.debug('event: {}'.format(event)) params = get_path_parameters(event) try: user_id = params['user_id'] context.repo.delete_user_in_supplier(context.supplier_id, user_id) return {'statusCode': 204} except NoSuchEntity as ex: return { 'statusCode': 404, 'body': json.dumps({'error': '{MSG}'.format(MSG=str(ex))}) } except NotAnAdminUser: return { 'statusCode': 403, 'body': json.dumps({'error': "Forbidden. Admins only"}) } except: logger.log_uncaught_exception()
def add_adjustment(event, context): """ Add adjustment inventory record """ logger.debug('event: {}'.format(event)) try: body = get_body(event) except json.JSONDecodeError: return { 'statusCode': 400, 'body': json.dumps({'error': 'Bad parameter(s) in request'}) } body["supplier_id"] = context.supplier_id try: body = context.repo.save_adjustment(body) return {'statusCode': 200, 'body': json.dumps(body)} except BadParameters as ex: key = str(ex) if key: return { 'statusCode': 400, 'body': json.dumps({ 'error': 'Bad request. The request was Malformed. Wrong type for key-val pair {KEY}' .format(KEY=key) }) } else: return { 'statusCode': 400, 'body': json.dumps({'error': 'Bad request. The request was Malformed'}) } except NoSuchEntity as ex: return { 'statusCode': 404, 'body': json.dumps({ 'error': '{RESOURCE} Resource not found'.format(RESOURCE=str(ex)) }) } except MissingRequiredKey as ex: return { 'statusCode': 400, 'body': json.dumps({ 'error': 'Bad request. Missing required key-val pair {KEY}'.format( KEY=str(ex)) }) }
def modify_purchase_order(event, context): """ Modify purchase order """ logger.debug('event: {}'.format(event)) try: body = get_body(event) except json.JSONDecodeError: return { 'statusCode': 400, 'body': json.dumps({'error': 'Bad parameter(s) in request'}) } try: item = context.repo.save_purchase_order(body) return {'statusCode': 200, 'body': json.dumps(item)} except BadParameters: return { 'statusCode': 400, 'body': json.dumps({'error': 'Bad request. The request was Malformed'}) } except MissingRequiredKey as ex: return { 'statusCode': 400, 'body': json.dumps({ 'error': 'Bad request. Missing required key-val pair {KEY}'.format( KEY=str(ex)) }) }
def get_by_id(event, context): """ Get a supplier by its id """ logger.debug('event: {}'.format(event)) params = get_path_parameters(event) try: entity_id = params['entity_id'] if context.supplier_id != entity_id: return { 'statusCode': 403, 'body': json.dumps({ 'error': 'Forbidden. x-supplier-id header must match entity_id' }) } item = context.repo.get_supplier_by_id(entity_id) return {'statusCode': 200, 'body': json.dumps(item)} except NoSuchEntity: return { 'statusCode': 404, 'body': json.dumps({'error': 'Resource not found'}) }
def get_by_id(event, context): """ Get an adjustment record by its id """ logger.debug('event: {}'.format(event)) params = get_path_parameters(event) try: entity_id = params['entity_id'] item = context.repo.get_adjustment_record_by_id( context.supplier_id, entity_id) return {'statusCode': 200, 'body': json.dumps(item)} except NoSuchEntity as ex: return { 'statusCode': 404, 'body': json.dumps({ 'error': '{RESOURCE} Resource not found'.format(RESOURCE=str(ex)) }) }
def charge_by_stripe(event, context): logger.debug('event: {}'.format(event)) try: body = get_body(event) except json.JSONDecodeError: return { 'statusCode': 400, 'body': json.dumps({'error': 'Bad parameter(s) in request'}) } email = body["email"] user_id = '00000000-0000-0000-0000-000000000000' try: repo = DynamoRepository( region_name=os.environ['REGION'], user_id=user_id, email=email, dynamodb_local_endpoint=os.environ['DYNAMO_ENDPOINT']) except KeyError: repo = DynamoRepository(region_name=os.environ['REGION'], user_id=user_id, email=email) resp = repo.charge_by_stripe(body) if 'status' in resp and resp['status'] == 'succeeded': return {'statusCode': 200, 'body': json.dumps(resp)} else: return {'statusCode': 500, 'body': json.dumps(resp)}
def get_inventory_csv(event, context): logger.debug('event: {}'.format(event)) try: body = get_body(event) except json.JSONDecodeError: return { 'statusCode': 400, 'body': json.dumps({'error': 'Bad parameter(s) in request'}) } try: inventory_csv_string = inventory_csv.generate(body) return { 'statusCode': 200, 'body': inventory_csv_string, 'isBase64Encoded': True } except AuroraSqlExecuteFailed: return { 'statusCode': 500, 'body': json.dumps({'error': 'Internal Error. SQL Execution failed'}) }
def delete_account(event, context): """ Delete user account """ logger.debug('event: {}'.format(event)) req = requests.post(os.environ['AUTH0_DOMAIN'] + '/oauth/token', json={ 'grant_type': 'client_credentials', 'audience': os.environ['AUTH0_AUDIENCE'], 'client_id': os.environ['AUTH0_MANAGEMENT_API_CLIENT_ID'], 'client_secret': os.environ['AUTH0_MANAGEMENT_API_CLIENT_SECRET'] }) logger.debug('Getting machine-to-machine application, ' 'access token.\nResponse: {}'.format(req.json())) jwt = req.json()['access_token'] headers = { 'Authorization': 'Bearer {}'.format(jwt), 'Content-Type': 'application/json', } if context.user_id.find('|') == -1: _auth0_user_id = 'auth0|' + context.user_id else: _auth0_user_id = context.user_id url = os.environ['AUTH0_DOMAIN'] + \ '/api/v2/users/' + _auth0_user_id resp = requests.delete(url, headers=headers) if resp.status_code != 204: return { 'statusCode': 400, 'body': json.dumps({ 'error': 'Something went wrong with deleting user account' }) # something went wrong with auth0 } try: context.repo.delete_profile() return {'statusCode': 204} except NoSuchEntity: return { 'statusCode': 404, 'body': json.dumps({'error': 'User not found'}) } except: logger.log_uncaught_exception()
def parse_multipart_req(body, content_type): """ Parse multipart-encoded form data """ req = {} # convert to bytes if needed if isinstance(body, str): body = bytes(body, "utf-8") multipart_data = decoder.MultipartDecoder(body, content_type) for part in multipart_data.parts: content_disposition = part.headers.get(b"Content-Disposition", b"") content_disposition = content_disposition.decode("utf-8") search_field = PATTERN.search(content_disposition) if search_field: if search_field.group(0) == "image": img_io = io.BytesIO(part.content) img_io.seek(0) req["image"] = img_io elif search_field.group(0) == "url": url = part.content.decode("utf-8") img_io = io.BytesIO(urlopen(url).read()) req["url"] = img_io elif search_field.group(0) == "bbox": req["bbox"] = json.loads(part.content.decode("utf-8")) else: logger.debug("Bad field name in form-data") return req
def modify_retail_package(event, context): logger.debug('event: {}'.format(event)) try: body = get_body(event) except json.JSONDecodeError: return { 'statusCode': 400, 'body': json.dumps({'error': 'Bad parameter(s) in request'}) } if "supplier_id" in body and body["supplier_id"] != context.supplier_id: return { 'statusCode': 400, 'body': json.dumps({ 'error': 'Bad parameter(s) in request. supplier_id in body must match x-supplier-id' }) } body["supplier_id"] = context.supplier_id try: item = context.repo.save_retail_package(body) return {'statusCode': 200, 'body': json.dumps(item)} except BadParameters as ex: key = str(ex) if key: return { 'statusCode': 400, 'body': json.dumps({ 'error': 'Bad request. The request was Malformed. Wrong type for key-val pair {KEY}' .format(KEY=key) }) } else: return { 'statusCode': 400, 'body': json.dumps({'error': 'Bad request. The request was Malformed'}) } except MissingRequiredKey as ex: return { 'statusCode': 400, 'body': json.dumps({ 'error': 'Bad request. Missing required key-val pair {KEY}'.format( KEY=str(ex)) }) }
def _is_valid_order(order): valid_order_length = const.valid_order_length if not (order.startswith('A') and len(order) == valid_order_length): logger.debug('ORDER NUMBER INCORRECT [%r]' % order) raise ValueError('ORDER NUMBER INCORRECT [%r]' % order) else: return order
def modify_brand(event, context): logger.debug('event: {}'.format(event)) try: body = get_body(event) except json.JSONDecodeError: return { 'statusCode': 400, 'body': json.dumps({ 'error': 'Bad parameter(s) in request' }) } if "supplier_id" in body and body["supplier_id"] != context.supplier_id: return { 'statusCode': 400, 'body': json.dumps({ 'error': 'Bad parameter(s) in request. supplier_id in body must match x-supplier-id' }) } body["supplier_id"] = context.supplier_id try: item = context.repo.save_brand(body) return { 'statusCode': 200, 'body': json.dumps(item) } except BadParameters as ex: return { 'statusCode': 400, 'body': json.dumps({ 'error': 'Bad request. The request was Malformed. Wrong type for key-val pair {KEY}'.format(KEY=str(ex)) }) } except UnsupportedMediaType: return { 'statusCode': 415, 'body': json.dumps({ 'error': 'Unsupported media type. Error with logo PNG. Unable to decode base64-PNG' }) } except MissingRequiredKey as ex: return { 'statusCode': 400, 'body': json.dumps({ 'error': 'Bad request. Missing required key-val pair {KEY}'.format(KEY=str(ex)) }) } except CannotModifyEntityStates: return { 'statusCode': 409, 'body': json.dumps({ 'error': 'A brand with the same name already exists' }) }
def get_every_production(event, context): """ Get all production entries """ logger.debug('event: {}'.format(event)) items = context.repo.get_all_production(context.supplier_id) return {'statusCode': 200, 'body': json.dumps(items)}
def get_every_count(event, context): """ Get all counts """ logger.debug('event: {}'.format(event)) items = context.repo.get_all_counts(context.supplier_id) return {'statusCode': 200, 'body': json.dumps(items)}
def get_every_distributor_supplier(event, context): """ Get all distributor_supplier """ logger.debug('event: {}'.format(event)) items = context.repo.get_all_distributor_suppliers(context.distributor_id) return {'statusCode': 200, 'body': json.dumps(items)}
def social_auth(event, context): logger.debug('event: {}'.format(event)) if os.environ['SIGNUP_ORIGIN_URL'] is not "*": # "*" means accept any origin # Check if the request is originating from a valid URI origin = event['headers']['origin'] valid_origin_uri = urlparse(os.environ['SIGNUP_ORIGIN_URL']) request_uri = urlparse(origin) if request_uri.netloc not in valid_origin_uri.netloc: logger.error("Request origin domain: {REQ_DOM}, " "Valid origin domain: {VALID_DOM}".format(REQ_DOM=request_uri.netloc, VALID_DOM=valid_origin_uri.netloc)) return { 'statusCode': 401, 'body': json.dumps({ 'error': 'Unauthorized. Request originating from invalid domain' }) } try: body = get_body(event) except json.JSONDecodeError: return { 'statusCode': 400, 'body': json.dumps({ 'error': 'Bad parameter(s) in request' }) } if 'connection' not in body or not body['connection'] or 'redirect_uri' not in body or not body['redirect_uri']: return { 'statusCode': 400, 'body': json.dumps({ 'error': 'Missing required key-value pair(s) in request body' }) } connection = body['connection'] redirect_uri = body['redirect_uri'] # token access right limited openid, profile, email query = (('client_id', os.environ['AUTH0_CLIENT_ID']), ('response_type', 'code'), ('connection', connection), ('scope', 'openid profile email'), ('redirect_uri', redirect_uri), ('state', 'xyzABC123')) return_url = os.environ['AUTH0_DOMAIN'] + '/authorize?' + urlencode(query).replace('+', '%20') return { 'statusCode': 200, 'body': json.dumps({ 'return_url': return_url }) }
def evaluate(sess, image_paths, embeddings, labels_batch, image_paths_placeholder, labels_placeholder, batch_size_placeholder, learning_rate_placeholder, phase_train_placeholder, enqueue_op, actual_issame, batch_size, nrof_folds, log_dir, step, summary_writer, embedding_size): start_time = time.time() # Run forward pass to calculate embeddings logger.debug('Running forward pass on LFW images: ') nrof_images = len(actual_issame) * 2 assert (len(image_paths) == nrof_images) labels_array = np.reshape(np.arange(nrof_images), (-1, 3)) image_paths_array = np.reshape(np.expand_dims(np.array(image_paths), 1), (-1, 3)) sess.run( enqueue_op, { image_paths_placeholder: image_paths_array, labels_placeholder: labels_array }) emb_array = np.zeros((nrof_images, embedding_size)) nrof_batches = int(np.ceil(nrof_images / batch_size)) label_check_array = np.zeros((nrof_images, )) for i in xrange(nrof_batches): batch_size = min(nrof_images - i * batch_size, batch_size) emb, lab = sess.run( [embeddings, labels_batch], feed_dict={ batch_size_placeholder: batch_size, learning_rate_placeholder: 0.0, phase_train_placeholder: False }) emb_array[lab, :] = emb label_check_array[lab] = 1 logger.debug('evaluate time: %.3f' % (time.time() - start_time)) assert (np.all(label_check_array == 1)) _, _, accuracy, val, val_std, far = lfw.evaluate(emb_array, actual_issame, nrof_folds=nrof_folds) logger.info('Accuracy: %1.3f+-%1.3f' % (np.mean(accuracy), np.std(accuracy))) logger.info('Validation rate: %2.5f+-%2.5f @ FAR=%2.5f' % (val, val_std, far)) lfw_time = time.time() - start_time # Add validation loss and accuracy to summary summary = tf.Summary() #pylint: disable=maybe-no-member summary.value.add(tag='lfw/accuracy', simple_value=np.mean(accuracy)) summary.value.add(tag='lfw/val_rate', simple_value=val) summary.value.add(tag='time/lfw', simple_value=lfw_time) summary_writer.add_summary(summary, step) with open(os.path.join(log_dir, 'lfw_result.txt'), 'at') as f: f.write('%d\t%.5f\t%.5f\n' % (step, np.mean(accuracy), val))
def add_user_to_supplier(event, context): """ Add a new/existing user to supplier """ logger.debug('event: {}'.format(event)) try: body = get_body(event) except json.JSONDecodeError: return { 'statusCode': 400, 'body': json.dumps({'error': 'Bad parameter(s) in request'}) } except: logger.log_uncaught_exception() try: body = context.repo.upsert_user_in_supplier(context.supplier_id, body) return {'statusCode': 204, 'body': json.dumps(body)} except BadParameters: return { 'statusCode': 400, 'body': json.dumps({'error': 'Bad request. The request was Malformed'}) } except Auth0AccessDenied: return { 'statusCode': 500, 'body': json.dumps({ 'error': "Unable to update Auth0. App doesn't have right scopes" }) } except Auth0UnknownError as ex: return { 'statusCode': 500, 'body': json.dumps({'error': "Auth0 Error: {ERROR}".format(ERROR=str(ex))}) } except Auth0UnableToAccess: return { 'statusCode': 500, 'body': json.dumps({'error': "Couldn't access Auth0"}) } except NotAnAdminUser: return { 'statusCode': 403, 'body': json.dumps({'error': "Forbidden. Admins only"}) } except: logger.log_uncaught_exception()
def add_merchandise(event, context): """ Add a new merchandise """ logger.debug('event: {}'.format(event)) try: body = get_body(event) except json.JSONDecodeError: return { 'statusCode': 400, 'body': json.dumps({'error': 'Bad parameter(s) in request'}) } except: logger.log_uncaught_exception() body["supplier_id"] = context.supplier_id try: body = context.repo.save_merchandise(body) return {'statusCode': 200, 'body': json.dumps(body)} except BadParameters as ex: return { 'statusCode': 400, 'body': json.dumps({ 'error': 'Bad request. The request was Malformed. Wrong type for key-val pair {KEY}' .format(KEY=str(ex)) }) } except MissingRequiredKey as ex: return { 'statusCode': 400, 'body': json.dumps({ 'error': 'Bad request. Missing required key-val pair {KEY}'.format( KEY=str(ex)) }) } except CannotModifyEntityStates: return { 'statusCode': 409, 'body': json.dumps( {'error': 'a merchandise with the same name already exists'}) } except: logger.log_uncaught_exception()
def add_production(event, context): """ Add a new product """ logger.debug('event: {}'.format(event)) try: body = get_body(event) except json.JSONDecodeError: return { 'statusCode': 400, 'body': json.dumps({'error': 'Bad parameter(s) in request'}) } body["supplier_id"] = context.supplier_id try: body = context.repo.save_production(body) return {'statusCode': 200, 'body': json.dumps(body)} except BadParameters as ex: return { 'statusCode': 400, 'body': json.dumps({ 'error': 'Bad request. The request was Malformed. Wrong type for key-val pair {KEY}' .format(KEY=str(ex)) }) } except MissingRequiredKey as ex: return { 'statusCode': 400, 'body': json.dumps({ 'error': 'Bad request. Missing required key-val pair {KEY}'.format( KEY=str(ex)) }) } except CannotModifyEntityStates: return { 'statusCode': 409, 'body': json.dumps({ 'error': 'The request could not be completed due to a conflict with the current state of the resource. ' 'This error could be because, a supplier with the same name already exists' }) }
def process_production_queue(event, context): """ Process production record in queue """ logger.debug('event: {}'.format(event)) logger.debug('event: {}'.format(context)) records = event['Records'] for record in records: repo, suppliers = get_repo(record) obj = json.loads(record['body']) repo.process_production_queue(obj)
def process_counts_queue(event, context): """ Delete count record by entity_id and version """ logger.debug('event: {}'.format(event)) logger.debug('event: {}'.format(context)) records = event['Records'] for record in records: repo, suppliers = get_repo(record) obj = json.loads(record['body']) repo.process_counts_queue(obj)