Exemple #1
0
def process_report():
    """Save reported crime to database."""

    time_input = request.args.get("time")
    date_input = request.args.get("date")
    address_input = request.args.get("address")
    description = request.args.get("description")
    map_category = request.args.get("map_category")

    time = datetime.strptime(time_input,"%H:%M").time() #format the time as a datetime object

    date = datetime.strptime(date_input, "%Y-%m-%d")    #format the date as a datetime object
    date_string = datetime.strftime(date,"%Y-%m-%d")    #format date as a string

    #use the Mapbox geocoder API to get the coordinates of the addressed inputted
    geocode = requests.get("https://api.tiles.mapbox.com/v4/geocode/mapbox.places/'%s'.json?access_token=pk.eyJ1IjoiYmh1c2hhbmgwMDciLCJhIjoiY2loZ3hhdWlxMG1mNHRjbHo2M2Z2Y2ZvdCJ9.nYBRCWB3gv-IjutuKYpTTg" % address_input)
    geocode_text = geocode.text     #put the response into text
    geocode_json = json.loads(geocode_text) #read in as json

    coordinates = geocode_json["features"][0]["geometry"]["coordinates"]    #this will return the coordinates of the first returned location, sometimes there is more than one, maybe deal with this later

    y_cord = coordinates[0]
    x_cord = coordinates[1]
    address = address_input

    data_source = "citizen"
    day_of_week = datetime.strftime(date,"%A")  #get a string with the day of the week
    month = datetime.strftime(date,"%B")        #get a string with the month
    hour = time.strftime("%H:00")               # get a string with the hour
    incident_id = Crime_Stat.query.order_by(desc(Crime_Stat.incident_id)).first().incident_id + 1

    #see if another user has submitted a report on the same date, at the dame location, at the same hour, and with the same category
    overlap = Crime_Stat.query.filter_by(date=date_string,x_cord=x_cord,y_cord=y_cord,hour=hour,map_category=map_category).all()

    #if so, do not update the database
    if overlap:
        
        return jsonify({"nothing":"nothing"})

    #if not, update the database with the citizen report and call the feature object method on the instance so there will be a marker passed to the map
    else:

        incident = Crime_Stat(incident_id=incident_id,data_source=data_source, description=description,map_category=map_category,day_of_week=day_of_week,date=date,
            month=month,time=time,hour=hour,address=address,x_cord=x_cord,y_cord=y_cord)
        
        db.session.add(incident)

        db.session.commit()

        feature_object = incident.make_feature_object()

        return jsonify(feature_object)