def alert(): alerts = iris_db.query(Alert) #alerts = [] if request.method == 'POST': if request.form['btn'] == 'New': return redirect(url_for('new_alert')) elif request.form['btn'] == 'Update': selected = request.form.getlist('selected') return redirect(url_for('update_alert', selected=selected)) elif request.form['btn'] == 'Promote': selected = request.form.getlist('selected') for s in selected: query = iris_db.query(Alert).filter(Alert.title == s) for q in query: alerts.append(q.to_ref()) #iris_db.remove(q) iris_db.insert( Incident(title=q.title, entered=q.entered, comments=q.comments, status="Promoted", itype=q.itype, alerts=alerts)) return render_template('alert/alert.html', title='Alert', alerts=alerts)
def create_incident_instance(row): i = Incident( incident_datetime=row['Incident Datetime'], incident_date=row['Incident Date'], incident_time=row['Incident Time'], incident_year=row['Incident Year'], incident_day_of_the_week=row['Incident Day of Week'], report_datetime=row['Report Datetime'], row_id=row['Row ID'], incident_id=row['Incident ID'], incident_number=row['Incident Number'], cad_number=row['CAD Number'], report_type_code=row['Report Type Code'], report_type_description=row['Report Type Description'], filed_online=row['Filed Online'], incident_code=row['Incident Code'], incident_category=row['Incident Category'], incident_subcategory=row['Incident Subcategory'], incident_description=row['Incident Description'], resolution=row['Resolution'], intersection=row['Intersection'], cnn=row['CNN'], police_district=row['Police District'], analysis_neighborhood=row['Analysis Neighborhood'], supervisor_district=row['Supervisor District'], latitude=row['Latitude'], longitude=row['Longitude'], point=row['point'], ) print("...adding Incident #%s, Row ID: %s" % (i.incident_id, i.row_id)) db.session.add(i) print("...adding Incident #%s, Row ID: %s" % (i.incident_id, i.row_id))
def handle_incident(): firststep=request.get_json() print(firststep) print(firststep["email"]) secondstep=User.query.filter(User.email==firststep["email"]).first() thridstep=Service.query.filter(Service.servicetype_name==firststep["servicetype_name"]).first() fourthstep=Incident(user_id=secondstep.user_id,servicetype_id=thridstep.servicetype_id,latitude=firststep["latitude"],longitude=firststep["longitude"]) db.session.add(fourthstep) db.session.commit() # getting a User's zipcode by using latitude & longitude responsepostal = requests.get("https://maps.googleapis.com/maps/api/geocode/json",params={'latlng':firststep["latitude"]+','+firststep["longitude"],'key':'AIzaSyDnPdnUPzUc0NaVzp4hS6Y_dhPSE8rvK1s'}) response1=responsepostal.json() list1=response1["results"][0]["address_components"] postal_code = None for obj in list1: if obj["types"][0]=="postal_code": postal_code = obj["long_name"] print(postal_code) if postal_code is not None: # its time to send the sms to everyone at this postal code heros_nearby = Hero.query.filter(Hero.zip_code==postal_code).all() for _hero in heros_nearby: print(_hero) send_sms("Hello "+_hero.first_name+", someone needs your help! please reply with "+str(fourthstep.incident_id)+" if you are willing to help", _hero.phone) return "success"
def run_test(endpoint_model, metrics_groups, alert_groups, endpoint_expected, endpoint_threshold): attempt = 0 keep_trying = True incident_timestamp = datetime.now(timezone.utc).astimezone().isoformat() original_endpoint_url = endpoint_model.url while keep_trying: if "##CUPCAKE_ATTEMPT##" in original_endpoint_url: endpoint_model.url = original_endpoint_url.replace( "##CUPCAKE_ATTEMPT##", str(attempt + 1)) result = test_endpoint(endpoint=endpoint_model, expected=endpoint_expected, threshold=endpoint_threshold, metrics_groups=metrics_groups) if not result["result"] and result["message"] == "TIMEOUT": attempt = attempt + 1 if attempt <= 3: logger.info( "re-testing timed out endpoint ({}) (attempt {} failed)". format(endpoint_model.url, attempt)) keep_trying = True continue break incident = Incident(timestamp=incident_timestamp, endpoint=endpoint_model, result=result, expected=endpoint_expected) handle_result(incident=incident, alert_groups=alert_groups)
def emit_summary(): """ Show a summary via a subset of notification types """ logger.info("emit summary") global endpoint_definitions global alert_definitions global db number_of_endpoints = 0 for group in endpoint_definitions["groups"]: for environment in group["environments"]: for endpoint_group in environment["endpoint-groups"]: if endpoint_group["enabled"] == "true": for _ in endpoint_group["endpoints"]: number_of_endpoints = number_of_endpoints + 1 endpoint_plural = "s" if number_of_endpoints == 1: endpoint_plural = "" message = "Cupcake is alive and currently monitoring {} endpoint{}.".format( number_of_endpoints, endpoint_plural) actives = db.get_all_actives() actives_message = "" for active in actives: actives_message = actives_message + "{} since {}\n".format( active["message"], datetime.utcfromtimestamp( active["timestamp"]).strftime('%Y-%m-%d %H:%M:%S')) if len(actives) == 0: message = message + "\n\nCupcake is not currently aware of any alerts." else: message = message + "\n\nCupcake is aware of the following alerts:\n%s" % actives_message deliver_alert_to_group(incident=Incident(timestamp=time.time(), message=message), alert_group_id="summary", alert_definitions=alert_definitions)
def new_incident_action (): if 'gcs_user' in session and session ['gcs_logged_in']: incident_title = request.form.get ('title') incident_title = incident_title.strip () description = request.form.get ('description').strip() description = description.strip () username_val = session ['gcs_user'] drone_sel_id = int(request.form.get ('drone_select')) username_id = GCSUser.query.filter_by (username = username_val).first().id drone_sel_name = Drone.query.filter_by (id = drone_sel_id).first ().drone_name priority_sel = request.form.get ('priority_sel') incident = Incident (incident_title,description,username_id,username_val, drone_sel_id,drone_sel_name,priority_sel) db.session.add (incident) db.session.commit () return redirect ('/incidents',code = 302) else: return redirect ('/gcslogin',code = 302)
def new_incident(): form = NewIncidentForm() if form.validate_on_submit(): title = form.title.data itype = form.itype.data entered = datetime.utcnow() comments = [form.comments.data] alerts = [] iris_db.insert( Incident(title=title, status="Manual", itype=itype, comments=comments, entered=entered, alerts=alerts)) return redirect(url_for('incident')) return render_template("incident/new_incident.html", title='New Incident', form=form)
def create(request): """Create Incident with IncidentLocation""" try: json_obj = commonHttp.get_json(request.body) # Check request json req_attrs = [ expectedAttr["DESC"], expectedAttr["TYPE"], expectedAttr["LOC"], ] commonHttp.check_keys(json_obj, req_attrs) new_location = None if json_obj.get(expectedAttr["LOC"]): new_location = create_location(json_obj.get(expectedAttr["LOC"])) activation_time = json_obj.get(expectedAttr["ACT_TIME"]) deactivation_time = json_obj.get(expectedAttr["DEACT_TIME"]) new_incident = Incident(activation_time=activation_time, deactivation_time=deactivation_time, description=json_obj[expectedAttr["DESC"]], incident_type=json_obj[expectedAttr["TYPE"]], location=new_location) commonHttp.save_model_obj(new_incident) response = JsonResponse({"id": new_incident.id, "success": True}) return response except commonHttp.HttpBadRequestException as e: return HttpResponseBadRequest(e.reason_phrase)
def photo_menu(photo): previous_incidents = (session.query(Incident).order_by( Incident.time.desc())) choices = [{ 'name': 'Create new Incident', 'value': 'new_incident', }] if previous_incidents.first(): choices.append({ 'name': 'Add to previous Incident', 'value': 'previous_incident', }) choices += [{ 'name': 'Ignore', 'value': 'ignore', }, { 'name': 'Main Menu', 'value': 'main_menu', }, { 'name': 'Quit', 'value': 'quit', }] choice = prompt({ 'type': 'list', 'name': 'item', 'message': 'Photo {}; {}'.format(photo.filename, photo.timestamp.astimezone(timezone)), 'choices': choices, })['item'] if choice == 'new_incident': incident = Incident(time=photo.timestamp) incident.photos.append(photo) session.add(incident) session.commit() incident_menu(incident) elif choice == 'previous_incident': incident = prompt({ 'type': 'list', 'name': 'incident', 'message': 'Previous Incidents', 'choices': [{ 'name': '{} {} {}'.format(i.time and i.time.astimezone(timezone), i.location and i.location.name, i.car and i.car.license_plate), 'value': i, } for i in previous_incidents] })['incident'] incident.photos.append(photo) session.commit() elif choice == 'ignore': photo.ignore = True session.commit() elif choice == 'main_menu': main_menu() elif choice == 'quit': sys.exit(0)