def forgot_password(): global telegram_chat_id new_password = '' letters = string.ascii_letters for i in range(12): character = random.choice(letters) new_password = new_password + character dynamodb = boto3.resource('dynamodb', region_name='us-east-1') table = dynamodb.Table('credentials') response = table.update_item( Key = { 'username': '******' }, UpdateExpression = "set password = :p, is_temp = :t", ExpressionAttributeValues = { ':p': new_password, ':t': 'true' }, ReturnValues = "UPDATED_NEW" ) message = {} message["default"] = 'Your new password is ' + new_password + '.' client.publish('password/reset', json.dumps(message), 1) bot.sendMessage(telegram_chat_id, 'We\'ve just received a password reset request! Go check your email for the temporary password. Once logged in, it is best you change it immediately.') return render_template("forgot-password.html")
def change_password_check(): if request.method == 'POST': try: dynamodb = boto3.resource('dynamodb', region_name='us-east-1') cur_password = request.form["currentPassword"] new_password = request.form["newPassword"] new_password_confirm = request.form["newPasswordConfirm"] table = dynamodb.Table('credentials') response = table.query(KeyConditionExpression = Key('username').eq('WateringPi'), ScanIndexForward = False ) results = response["Items"] stored_password = results[0]["password"] if cur_password == stored_password and new_password == new_password_confirm: response = table.update_item( Key = { 'username': '******' }, UpdateExpression = "set password = :p, is_temp = :t", ExpressionAttributeValues = { ':p': new_password, ':t': 'false' }, ReturnValues = "UPDATED_NEW" ) global telegram_chat_id bot.sendMessage(telegram_chat_id, 'Your WateringPi password was changed. If it wasn\'t you who changed the password, reset it immediately.') response = make_response(redirect('/password_changed/')) return response else: response = make_response(redirect('/change_password/')) return response except: print(sys.exc_info()[0]) print(sys.exc_info()[1])
def update_user_prefs(): if request.method == 'POST': try: dynamodb = boto3.resource('dynamodb', region_name='us-east-1') table = dynamodb.Table('user_preferences') soil_interval = request.form['soilInterval'] environment_interval = request.form['environmentInterval'] photo_interval = request.form['photoInterval'] dry_soil_threshold = request.form['minimumMoisture'] watering_duration = request.form['wateringDuration'] response = table.update_item( Key = { 'name': 'default' }, UpdateExpression = "set soil_refresh_interval = :s, environment_refresh_interval = :e, photo_interval = :p, dry_soil_threshold = :t, watering_duration = :w", ExpressionAttributeValues = { ':s': soil_interval, ':e': environment_interval, ':p': photo_interval, ':t': dry_soil_threshold, ':w': watering_duration }, ReturnValues = "UPDATED_NEW" ) response = make_response(redirect("/")) return response except: print(sys.exc_info()[0]) print(sys.exc_info()[1])
def get_user_prefs(): dynamodb = boto3.resource('dynamodb', region_name='us-east-1') table = dynamodb.Table('user_preferences') deviceid = 'deviceid_dorachua' response = table.query(KeyConditionExpression = Key('name').eq('default'), ScanIndexForward = False ) results = response["Items"] return jsonify(results)
def lambda_handler(event, context): logger.info("Event: " + str(event)) trigger = json.loads(event['Records'][0]['Sns']['Message'])['Trigger'] logger.info("Trigger: " + json.dumps(trigger, indent=4)) metricName = trigger['MetricName'] namespace = trigger['Namespace'] dimensions = trigger['Dimensions'] if namespace != cloudwatch.NAMESPACE: raise Exception("Namespace is not match: " + namespace) metric = cloudwatch.Metrics(dimensions, metricName) provision = metric.calcProvision() table = dynamodb.Table(metric.dimensions) table.update(metric.name, provision) for key in cloudwatch.BOUNDARIES.keys(): metric.alarm(key).update(provision)
def apidata_get_soil_data(): if request.method == 'POST' or request.method == 'GET': try: dynamodb = boto3.resource('dynamodb', region_name='us-east-1') table = dynamodb.Table('soilmoisture') startdate = '2019-08' response = table.query( KeyConditionExpression=Key('device_id').eq('raspberrypi-1') & Key('datetime_id').begins_with(startdate), ScanIndexForward=False ) items = response['Items'] n=75 # limit to last 10 items data = items[:n] data_reversed = data[::-1] response = data_reversed[0] return jsonify(data_reversed) except: import sys print(sys.exc_info()[0]) print(sys.exc_info()[1])
def login_check_credentials(): if request.method == 'POST': try: dynamodb = boto3.resource('dynamodb', region_name='us-east-1') password = request.form["password"] table = dynamodb.Table('credentials') response = table.query(KeyConditionExpression = Key('username').eq('WateringPi'), ScanIndexForward = False ) results = response["Items"] stored_password = results[0]["password"] if password == stored_password: response = make_response(redirect('/')) response.set_cookie('logged_in', 'True') return response else: global telegram_chat_id bot.sendMessage(telegram_chat_id, 'Someone unsuccessfully tried to log in to your WateringPi. If you see this message a few more times and it wasn\'t you trying to login, it might be someone trying to gain unauthorised access to your WateringPi. Consider changing the password to make your WateringPi more secure.') response = make_response(redirect('/login_page')) return response except: print(sys.exc_info()[0]) print(sys.exc_info()[1])
def predictSafety(bid): try: # Obtain SQL Reading for selected BookingID (SQLQuery) # https://www.kite.com/python/answers/how-to-convert-an-sql-query-result-to-a-pandas-dataframe-in-python # https://stackoverflow.com/questions/12047193/how-to-convert-sql-query-result-to-pandas-data-structure dynamodb = boto3.resource('dynamodb', region_name='us-east-1') table = dynamodb.Table('modedata') response = table.query(KeyConditionExpression=Key('bookingid').eq(bid)) datarows = response['Items'] df = pd.DataFrame(datarows, dtype=float) #resoverall is yr sql statement # df = DataFrame(resoverall.fetchall()) # df.columns = resoverall.keys() df.drop(['accuracy'], axis=1, inplace=True) df['acceleration'] = np.sqrt( (df.loc[:, ('acceleration_x', 'acceleration_y', 'acceleration_z')]**2).sum(axis=1)) df.drop([ 'acceleration_x', 'acceleration_y', 'acceleration_z', 'speedkmhour' ], axis=1, inplace=True) pca_gyro = PCA(n_components=1).fit( df.loc[:, ['gyro_x', 'gyro_y', 'gyro_z']]) df['gyro'] = pca_gyro.transform(df.loc[:, ('gyro_x', 'gyro_y', 'gyro_z')]) df.drop(['gyro_x', 'gyro_y', 'gyro_z'], axis=1, inplace=True) data = pd.DataFrame() for col in df.columns: if col != "bookingid" and col != "label": temp = df.groupby("bookingid")[col].agg( ["mean", "sum", "max", "min"]) data[col + "_mean"] = temp["mean"] data[col + "_sum"] = temp["sum"] data[col + "_max"] = temp["max"] data[col + "_min"] = temp["min"] #data = data.drop(columns=["bookingid"]).reset_index(drop=True) data.drop(columns=["seconds_min"], inplace=True) # generate distance, velocity and angle features for col in data.columns: if col.startswith("seconds"): agg_method = col.split("_")[1] data["distance_" + agg_method] = data[col] * data["speed_" + agg_method] data["velocity_" + agg_method] = data[col] * data["acceleration_" + agg_method] data["angle_" + agg_method] = data[col] * data["gyro_" + agg_method] data = data.drop(columns=['seconds_sum', 'seconds_mean']).reset_index( drop=True) # Once Obtain model after hyper tuning save weights here and predict from joblib import load sr = load("GBR.joblib") y_pred = sr.predict(data) print("regression value: ", y_pred[0]) return jsonify(json.loads(jsonc.data_to_json(y_pred[0]))) except: print(sys.exc_info()[0]) print(sys.exc_info()[1])