def new_alert(): form = NewAlertForm() #mongoalchemy #alerts = session.query(Alert).filter(Alert.name == 'Second_Alert') new = 'New' if form.validate_on_submit(): title = form.title.data ip = [form.ip.data] mac = [form.mac.data] atype = [form.atype.data] entered = datetime.utcnow() comments = [form.comments.data] print title #mongoalchemy iris_db.insert( Alert(title=title, ip=ip, mac=mac, status=new, atype=atype, comments=comments, entered=entered)) return redirect(url_for('alert')) return render_template("alert/new_alert.html", title='New Alert', form=form)
def get_alert(): # get request if request.method == 'GET': all_alerts = Alert.query.all() all_alerts = list(map(lambda x: x.serialize(), all_alerts)) return jsonify(all_alerts), 200 if request.method == 'POST': body = request.get_json() if body is None: raise APIException("Specify JSON body", status_code=400) if "message" not in body: raise APIException("Specify Message", status_code=400) if "email" not in body: raise APIException("Specify Email", status_code=400) alert1 = Alert(message=body['message'], email=body['email'], name=body['name'], petname=body['petname'], phone=body['phone']) db.session.add(alert1) db.session.commit() # print('kevin', alert1.__repr__()) return "ok", 200 return "invalid method", 404
def alert_list(): alerts = Alert.query.order_by(Alert.alert_id.desc()).all() if request.method == 'POST': content = request.form['alert'] alert = Alert(alert_content=content) db.session.add(alert) db.session.commit() return redirect(url_for("admin_app.alert_list")) return render_template('admin/alert/alert_list.html', alerts=alerts)
def addAlert(): deviceID = request.form['deviceID'] personNo = request.form['personNo'] confidence = request.form['confidence'] new_alert = Alert(deviceID, personNo, confidence) from myapp import db db.session.add(new_alert) db.session.commit() return jsonify({"deviceID":deviceID, "personNo":personNo, "confidence":confidence})
def add_alert(bot, update, market_id=None, price=None): if market_id is None: return market_list(update, 'add_alert') chat = get_chat(update) if chat.market_id != market_id: chat.market_id = market_id session.commit() market = chat.market if price is None: text = "_Precio actual = {} {}_".format(market.ask, market.currency) update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN) return update.message.reply_text(ALERT_INPUT_TEXT, reply_markup=ForceReply()) try: price = round(float(price), market.decimals) if price % 1 == 0: price = int(price) if price <= 0: raise ValueError except ValueError: update.message.reply_text("El precio debe ser un número mayor a 0.") return update.message.reply_text(ALERT_INPUT_TEXT, reply_markup=ForceReply()) if chat.alert_count() == MAX_ALERT_NUMBER: text = "Lo siento, sólo puedes agregar un máximo de {} /alertas.".format( MAX_ALERT_NUMBER) return update.message.reply_text(text) market = chat.market alert = chat.get_alert(market, str(price)) if alert is None: # Create alert only if it doesn't exist alert_data = { 'chat': chat, 'market': market, 'price': str(price), 'trigger_on_lower': price <= float(market.ask) } alert = Alert(**alert_data) session.add(alert) session.commit() values = { 'coin': market.coin, 'sign': '<' if alert.trigger_on_lower else '>', 'price': price, 'currency': market.currency, } text = "Perfecto, te enviaré una alerta si\n*1 {coin} {sign} {price} {currency}*".format( **values) keyboard = [[ InlineKeyboardButton("Añadir otra alerta", callback_data='add_alert {}'.format(market.id)), InlineKeyboardButton("Ver alertas", callback_data='alert_list') ]] update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(keyboard))
def settings(request): if request.method == 'POST': form = SettingsForm(request.POST) if form.is_valid(): try: Alert.objects.get(user=request.user).delete() except: pass data = form.cleaned_data client_t = data['user_time'] server_t = datetime.now().strftime('%H') tz_diff = int(server_t) - int(client_t) as_time = datetime(2013, 1, 1, data['time'].hour, data['time'].minute) as_time = as_time + timedelta(hours=tz_diff) a = Alert( user=request.user, alert_server_time=as_time, start=data['start'], finish=data['finish'], period=data['period'], time=data['time'], alert_email=data['alert_email'], email=data['email'], alert_sms=data['alert_sms'], phone=data['phone'] ) alert = {} try: a.save() alert['txt'] = 'Настройки сохранены' alert['cls'] = 'alert-success' except: alert['txt'] = 'Не удалось сохранить настройки, попробуйте повторить позже' alert['cls'] = 'alert-danger' return render_to_response('settings.html', {'form': form, 'alert': alert}, RequestContext(request)) else: try: a = Alert.objects.get(user=request.user) form = SettingsForm(instance=a) except: form = SettingsForm() return render_to_response('settings.html', {'form': form}, RequestContext(request))
def subscribe(argument): """Search: Filter post by user""" if argument not in ["S", "U"]: abort(405) user = get_user(session.get("user_id"), db_session) sub = db_session.query(Alert).filter(Alert.user_id == user.id_).first() if argument == "S": if sub is None: sub = Alert(user.id_) db_session.add(sub) db_session.commit() elif argument == "U": if sub is not None: db_session.delete(sub) db_session.commit() return redirect(url_for('user', id=user.id_))
def alert(client, userdata, msg): # unpack json payload json_data = msg.payload raw_data = json.loads(str(json_data, encoding="utf-8")) with app.app_context(): device = Device.query.filter_by(name=raw_data["serial-number"]).first() alert = Alert(deviceID=device.ID, personNo=raw_data["personNo"], confidence=raw_data["confidence"]) db.session.add(alert) db.session.commit() deviceID = device.ID alertID = alert.alertID personNo = alert.personNo confidence = alert.confidence time = alert.time #save alert image os.makedirs(app.config['MQTT_IMG_PATH'], exist_ok=True) img_path = app.config['MQTT_IMG_PATH'] + 'alert-' + str(alertID) + '.gif' base64_string = raw_data["image_base64_string"] img_data = base64.b64decode(base64_string) with open(img_path, 'wb') as imgf: imgf.write(img_data) # notify HTTP server in localhost payload = { 'deviceID': deviceID, 'alertID': alertID, 'time': time.isoformat(' ', 'seconds'), # 'alertInfo':{ # 'personNo': personNo, # 'confidence':confidence, # } } print(payload) requests.post("http://127.0.0.1:" + str(app.config['PORT']) + "/device/alert", headers={"Content-Type": "application/json"}, data=json.dumps(payload))
def parse_upload(directory, filename): #note: not taking into account that ip,mac,... can be a list or our we forcing one value one column for this with open(directory + '/' + filename) as f: records = csv.DictReader(f) for r in records: title = r['title'] status = r['status'] ip = [r['ip']] mac = [r['mac']] atype = [r['atype']] entered = datetime.utcnow() comments = [r['comments']] iris_db.insert( Alert(title=title, ip=ip, mac=mac, status=status, atype=atype, comments=comments, entered=entered))
def post(self): """ Create a new alert """ global users_connected json_data, error = get_data(request) if not error: device_data, error = validate_json_payload(json_data, self.fields) if not error: error = self.validate_jetson_data(device_data, data_dict={ 'truck_id': device_data['truck_id'], 'behavior': device_data['behavior'], 'date_': device_data['alert_init'] }) if not error: try: alert_data = self.alert_schema.load({ 'truck_id': device_data['truck_id'], 'behavior': device_data['behavior'], 'alert_init': device_data['alert_init'] }) except marshmallow.exceptions.ValidationError as errors: return response(400, str(errors)) alert = Alert(**alert_data) error = alert.save() if not error: # TODO: add alert.id to msg alert_event_notify(socket_obj, users_connected) return response(200, data={'alert_id': alert.id}) return error
def start_alert(self): start_time = datetime.now() arm = self._db_session.query(Arm).filter_by(end_time=None).first() self._alert = Alert(arm=arm, start_time=start_time, sensors=[]) self._db_session.add(self._alert) self._db_session.commit() self.handle_sensors() send_alert_state(self._alert.serialize) self._syren.alert(True) send_syren_state(True) self._logger.debug("Alerting sensors: %s", self._alert.sensors) sensor_descriptions = list( map( lambda item: f"{item.sensor.description}(id:{item.sensor.id}/CH{item.sensor.channel+1})", self._alert.sensors, ) ) Notifier.notify_alert_started(self._alert.id, sensor_descriptions, start_time) self._logger.info("Alert started")
def create_alert(): if request.method == 'POST': body = request.form.get('body') file = request.files['file'] alert = Alert(body=body, author=current_user.login) db.session.add(alert) db.session.commit() photo = Photos(link=(UPLOAD_FOLDER + '/' + slugify(str(alert.created), '') + file.filename), alert_id=alert.id) db.session.add(photo) db.session.commit() file.save( os.path.join(UPLOAD_FOLDER, slugify(str(alert.created), '') + file.filename)) last_post = Post.query.order_by(Post.id.desc()).first() last_alert = Alert.query.order_by(Alert.id.desc()).first() return render_template('create_alert.html', last_post=last_post, last_alert=last_alert, weekDays=rusWeekDays, months=rusMonths)
from twilio.rest import Client import os from models import Alert, Person Q = Alert() def first_function(number, mess): account_sid = os.environ.get('SID_KEV') auth_token = os.environ.get('TOKEN_KEV') client = Client(account_sid, auth_token) message = client.messages \ .create( body=mess, from_='+12064660790', to=number ) print(message.sid) # return repr(Q._queue)
def _create_alerts(data, person, unit): print "Creating alerts!" try: alerts = data['alerts'] if not isinstance(alerts, (list, tuple)): raise ValidationError("Problems not in list format") except KeyError: alerts = [] errors = [] for alert in alerts: comments = None try: emplid = alert['emplid'] code = alert['code'] description = alert['description'] unique_id = alert['unique_id'] except KeyError: raise ValidationError("Necessary fields not present in alert: " + str(alert)) try: if not isinstance(emplid, int): raise ValidationError("Alert emplid:'%s' must be integer" % str(emplid)) try: student = Person.objects.get(emplid=emplid) except Person.DoesNotExist: try: p = coredata.queries.add_person(emplid) except SIMSProblem: raise ValidationError( "Person %s could not be found; SIMS not working." % str(emplid)) except IOError: raise ValidationError( "Person %s could not be found; SIMS not working." % str(emplid)) if not isinstance(code, basestring) or not isinstance( description, basestring): raise ValidationError( "Alert code & description must be strings") if len(code) >= 30: raise ValidationError( "Alert code must be less than or equal to 30 characters") try: details = alert['details'] except KeyError: details = {} try: alertType = AlertType.objects.get(code=code) except AlertType.DoesNotExist: # If the AlertType doesn't exist, try to create one. # This requires that the User has provided a unit at the # base level of the JSON alertType = AlertType() alertType.code = code alertType.unit = unit alertType.description = "Not set." alertType.save() alert = Alert() alert.person = student alert.alerttype = alertType alert.description = description alert.details = details alert.safe_create(unique_id) except ValidationError as e: print e errors.append(str(e)) return errors
def add_info(form): item = 0 oid = form['oid'] iid = str(time.time())[:9] + str(random.randint(10, 99)) score = 0 if float(form['toxic']) > 30: score += 1 item += pow(2, 5) elif float(form['toxic']) > 28: score += 0.1 item += pow(2, 5) elif float(form['toxic']) > 25: score += 0.01 item += pow(2, 5) if float(form['med']) < 90: score += 1 item += pow(2, 4) elif float(form['med']) < 93: score += 0.1 item += pow(2, 4) elif float(form['med']) < 95: score += 0.01 item += pow(2, 4) if float(form['water']) < 73: score += 1 item += pow(2, 3) elif float(form['water']) < 75: score += 0.1 item += pow(2, 3) elif float(form['water']) < 80: score += 0.01 item += pow(2, 3) if float(form['temp']) > 4 or float(form['temp']) < -0.5: score += 1 item += pow(2, 2) elif float(form['temp']) > 3.5 or float(form['temp']) < 0: score += 0.1 item += pow(2, 2) elif float(form['temp']) != 1: score += 0.01 item += pow(2, 2) if float(form['moist']) > 95 or float(form['moist']) < 85: score += 1 item += pow(2, 1) elif float(form['moist']) > 93 or float(form['moist']) < 87: score += 0.1 item += pow(2, 1) elif float(form['moist']) != 90: score += 0.01 item += pow(2, 1) if int(form['store']) > 14: score += 1 item += pow(2, 0) elif int(form['store']) > 10: score += 0.1 item += pow(2, 0) elif int(form['store']) > 7: score += 0.01 item += pow(2, 0) level = 0 if score > 2: level = 4 elif score > 0.2: level = 3 elif score > 0.02: level = 2 else: level = 1 new_info = Info( toxic=form['toxic'], med=form['med'], water=form['water'], moist=form['moist'], store=form['store'], temp=form['temp'], iid=iid, level=level, oid=oid, ) order = Order.query.filter_by(oid=oid).first() order.iid = iid db.session.add(new_info) db.session.commit() if level != 0: aids = db.session.query(Admin.aid).all() for i in aids: new_alert = Alert( msgfor=2, toid=str(i[0]), msg=ALERT_MSG[level-1], title=ALERT_TITLE[level-1], oid=oid, item=item, valid=1, level=level-1, iid=iid, ) order.alevel = level-1 db.session.add(new_alert) db.session.commit() return redirect(url_for("superadd_page"))