Beispiel #1
0
def update_animal():
    if request.method == 'POST':
        #get Animal_ID, the only required query parameter
        animalid = str(request.args.get('Animal_ID'))
        #raise exception if user does not provide Animal_ID
        if not animalid:
            raise Exception('Animal_ID must be one of the query parameters')
        #iterate over all keys in raw data db
        for key in rd1.keys():
            #return "checking for animal id match"
            #find animal that matches the Animal_ID parameter
            if str(rd1.hget(key, 'Animal_ID'))[1:] == "'" + animalid + "'":
                #return "found animal match"
                #iterate over all field:value pairs passed in the query string
                for field, value in request.args.items():

                    #skip the Animal_ID field
                    if field == 'Animal_ID':
                        pass
                    #update the database for any other field that is passed in the query
                    else:
                        rd1.hset(key, field, value)
                return "You have edited animal " + animalid
        else:
            return "cannot find animal"

    else:
        return """
Beispiel #2
0
def execute_job(jid):
     
    data = jobs.get_job_data(jid)

    # call matplotlib to make a plot of something 
    # plot stuff here...
    start = data['start']
    end = data['end']

    # pplot the counts of each type of animal adopted in between a date range
    animal_types = ['Bird', 'Cat', 'Dog', 'Livestock', 'Other']
    animal_counts = [0, 0, 0, 0, 0]

    for key in rd1.keys():
        if (start <= key[DateTime].decode('utf-8') <= end):
             this_animal_type = key['Animal_Type']
             if this_animal_type == 'Bird':
                 animal_counts[0] += 1
             else if this_animal_type == 'Cat':
                 animal_counts[1] += 1
             else if this_animal_type == 'Dog':
                 animal_counts[2] += 1
             else if this_animal_type == 'Livestock':
                 animal_counts[3] += 1
             else if this_animal_type == 'Other':
                 animal_counts[4] += 1


    plt.clf()
    plt.bar(animal_types, animal_counts, color='green')
    plt.xlabel('Animal Type')
    plt.ylabel('Frequency')
    #plt.title('Amino Acid Frequency')
    #plt.xticks(aas_pos, aas)

    plt.savefig('/output_image.png')
    with open('/output_image.png', 'rb') as f:
        img = f.read()
    
    rd.hset(f'job.{jid}', 'result', img)
    jobs.update_job_status(jid, "completed")
Beispiel #3
0
def execute_job(jid):

    data = jobs.get_job_data(jid)

    job_type = jobs.get_job_type(jid)

    #analysis: plot total number of outcomes for each day in date range

    if (job_type == 'dates'):

        start = jobs.get_job_start(jid)
        end = jobs.get_job_end(jid)
        start_date = datetime.datetime.strptime(start, "%m-%d-%Y")
        end_date = datetime.datetime.strptime(end, '%m-%d-%Y')

        consecutive_dates = [
            start_date + datetime.timedelta(days=x)
            for x in range((end_date - start_date).days + 1)
        ]

        list_of_all_dates = []

        for key in rd1.keys():

            key_time_temp = rd1.hget(
                key, 'Date_of_Entry').decode('utf-8').split()[0]
            key_time = datetime.datetime.strptime(key_time_temp, '%m-%d-%Y')
            list_of_all_dates.append(key_time)

        list_of_outcomes_of_the_day = [0] * len(consecutive_dates)

        x_labeler = []

        for i in range(len(consecutive_dates)):
            list_of_outcomes_of_the_day[i] = list_of_all_dates.count(
                consecutive_dates[i])
            x_labeler.append(i)

        #consecutive_date_strings = []

        #for item in consecutive_dates:
        #    consecutive_date_strings.append(item.strftime("%m-%d-%Y"))

        plt.clf()
        plt.bar(x_labeler, list_of_outcomes_of_the_day, color='green')
        plt.xlabel('Days since Start')
        plt.ylabel('# Outcomes per Day')
        plt.title('Outcome Occurences by Day \n' + start + ' - ' + end)

        plt.savefig('/outcomes_by_animal_type.png')

        with open('/outcomes_by_animal_type.png', 'rb') as f:
            img = f.read()

        rd.hset(f'job.{jid}', 'result', img)

        jobs.update_job_status(jid, 'complete')

    #analysis: plot total # of outcomes by type of animal in date range
    if (job_type == 'animal_type'):

        #jobs.update_job_status(jid, 'it has entered the for loop')

        animal_types = ['Bird', 'Cat', 'Dog', 'Livestock', 'Other']
        animal_counts = [0, 0, 0, 0, 0]

        for key in rd1.keys():

            #jobs.update_job_status(jid, str(key))#'it has entered the for loop')

            this_animal_type = str(rd1.hget(key, 'Animal_Type'))[1:]

            #jobs.update_job_status(jid, str(this_animal_type))

            if this_animal_type == "'Bird'":
                animal_counts[0] += 1
            elif this_animal_type == "'Cat'":
                animal_counts[1] += 1
            elif this_animal_type == "'Dog'":
                animal_counts[2] += 1
            elif this_animal_type == "'Livestock'":
                animal_counts[3] += 1
            elif this_animal_type == "'Other'":
                animal_counts[4] += 1

        #jobs.update_job_status(jid, str(animal_counts))

        plt.clf()
        plt.bar(animal_types, animal_counts, color='green')
        plt.xlabel('Animal Type')
        plt.ylabel('Frequency')
        plt.title('Outcomes by Animal Type')

        plt.savefig('/outcomes_by_animal_type.png')

        with open('/outcomes_by_animal_type.png', 'rb') as f:
            img = f.read()

        rd.hset(f'job.{jid}', 'result', img)

        jobs.update_job_status(jid, 'complete')
Beispiel #4
0
def delete_animal():
    if method == 'DELETE':
        animal_to_delete = request.args.get('Animal_ID')
        for key in rd1.keys():
            if rd1.hget(key, 'Animal_ID') == animal_to_delete:
                rd1.hdel(key) # or maybe rd1.delete()
Beispiel #5
0
def update_animal():
    if method == 'POST':
        animalid = str(request.args.get('Animal_ID'))
        field_to_update = request.args.keys() # joe look this up

        for key in rd1.keys():
            if rd1.hget(key, 'Animal_ID') == animalid:
                rd1.hset(key, field_to_update, value_to_update)
    else:
    return """

    Try a curl command like:

    curl localhost:5000/update_animal?Animal_ID=A643424&Animal_Type=Dog


"""

# need a delete route
@app.route('/delete_animal', methods=['DELETE'])
def delete_animal():
    if method == 'DELETE':
        animal_to_delete = request.args.get('Animal_ID')
        for key in rd1.keys():
            if rd1.hget(key, 'Animal_ID') == animal_to_delete:
                rd1.hdel(key) # or maybe rd1.delete()












@app.route('/get_results',methods=['GET'])
def get_result():
    jid = str(request.args.get('Job_ID'))
    return json.dumps(jobs.get_result(jid))


@app.route('/jobs', methods=['POST'])
def jobs_api():
    try:
        job = request.get_json(force=True)
    except Exception as e:
        return True, json.dumps({'status': "Error", 'message': 'Invalid JSON: {}.'.format(e)})
    return json.dumps(jobs.add_job(job['start'], job['end']))

# user should do a curl request like:
# curl ip_address:5000/jobs -X POST -H "content-type: application/json" -d '{"start": "9/26/2018", "end": "9/26/2019"}'


@app.route('/download/<jobid>', methods=['GET'])
def download(jobid):
    path = f'/app/{jobid}.png'
    with open(path, 'wb') as f:
        f.write(rd.hget(jobid, 'image'))
    return send_file(path, mimetype='image/png', as_attachment=True)



if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')
Beispiel #6
0
def execute_job(jid):

    data = jobs.get_job_data(jid)

    job_type = jobs.get_job_type(jid)

    #jobs.update_job_status(jid, job_type)#'in progress')

    #analysis: plot total number of outcomes for each day in date range

    #first job type: dates
    if (job_type == 'dates'):

        #jobs.update_job_status(jid, 'entered first if statement')

        start = jobs.get_job_start(jid)
        end = jobs.get_job_end(jid)

        #set inital outcomes count
        animal_outcomes_of_day = 0

        #x values: list of dates
        x_values_to_plot = []

        #y values: list of integer numbers of outcomes per date
        y_values_to_plot = []

        start_date = datetime.datetime.strptime(start, "%m-%d-%Y")
        end_date = datetime.datetime.strptime(end, '%m-%d-%Y')

        #format to check for full day
        for key in rd1.keys():

            #jobs.update_job_status(jid, 'you have entered first for loop')

            #decode time to a string without hours and minutes
            key_time_temp = rd1.hget(
                key, 'Date_of_Entry').decode('utf-8').split()[0]
            #string to datetime
            key_time = datetime.datetime.strptime(key_time_temp, '%m-%d-%Y')

            #jobs.update_job_status(jid, str(key_time))

            #check for keys in date range
            if (start_date <= key_time and end_date >= key_time):

                #jobs.update_job_status(jid, 'this is entering 2nd if statement')

                #set specific date
                x = key_time_temp

                #jobs.update_job_status(jid, x)

                #check if date is alread in x_values_to_plot
                if x not in x_values_to_plot:

                    #jobs.update_job_status(jid, 'this is entering 3rd if statement')

                    #if new date: add to list of x_values_to_plot
                    x_values_to_plot.append(x)

                    #check through db for each animal with matching Date_of_Entry
                    for i in range(rd1.dbsize()):

                        #jobs.update_job_status(jid, 'this is entering 2nd for loop')

                        #issue with formatting?
                        if (x == rd1.hget(
                                i,
                                'Date_of_Entry').decode('utf-8').split()[0]):

                            #jobs.update_job_status(jid, 'this is entering 4th if statement')

                            #increment animal_outcomes_of_day count
                            animal_outcomes_of_day = animal_outcomes_of_day + 1

                    #finalize count for the day
                    y = animal_outcomes_of_day

                    #add total count to list of y_values_to_plot
                    y_values_to_plot.append(y)

                #reset animal_outcomes_of_day count before moving to next day
                animal_outcomes_of_day = 0

        jobs.update_job_status(jid, 'we have exited first loop')

        #plot scatter plot
        plt.scatter(x_values_to_plot, y_values_to_plot)

        plt.savefig('/outcomes_by_date.png')

        with open('/outcomes_by_date.png', 'rb') as f:
            img = f.read()

        rd.hset(f'job.{jid}', 'result', img)

        jobs.update_job_status(jid, 'complete')

    #analysis: plot total # of outcomes by type of animal in date range
    if (job_type == 'animal_type'):

        #jobs.update_job_status(jid, 'it has entered the for loop')

        animal_types = ['Bird', 'Cat', 'Dog', 'Livestock', 'Other']
        animal_counts = [0, 0, 0, 0, 0]

        for key in rd1.keys():

            #jobs.update_job_status(jid, str(key))#'it has entered the for loop')

            this_animal_type = str(rd1.hget(key, 'Animal_Type'))[1:]

            #jobs.update_job_status(jid, str(this_animal_type))

            if this_animal_type == "'Bird'":
                animal_counts[0] += 1
            elif this_animal_type == "'Cat'":
                animal_counts[1] += 1
            elif this_animal_type == "'Dog'":
                animal_counts[2] += 1
            elif this_animal_type == "'Livestock'":
                animal_counts[3] += 1
            elif this_animal_type == "'Other'":
                animal_counts[4] += 1

        #jobs.update_job_status(jid, str(animal_counts))

        plt.clf()
        plt.bar(animal_types, animal_counts, color='green')
        plt.xlabel('Animal Type')
        plt.ylabel('Frequency')
        plt.title('Outcomes by Animal Type')

        plt.savefig('/outcomes_by_animal_type.png')

        with open('/outcomes_by_animal_type.png', 'rb') as f:
            img = f.read()

        rd.hset(f'job.{jid}', 'result', img)

        jobs.update_job_status(jid, 'complete')
Beispiel #7
0
def execute_job(jid):

    data = jobs.get_job_data(jid)

    job_type = jobs.get_job_type(jid)

    #jobs.update_job_status(jid, job_type)#'in progress')

    #analysis: plot total number of outcomes for each day in date range

    #first job type: dates
    if (job_type == 'dates'):
        #jobs.update_job_status(jid, str(data))
        #jobs.update_job_status(jid, 'You have entered the if statement')
        #format of how dates come in??????????? should be a string
        start = jobs.get_job_start(jid)
        end = jobs.get_job_end(jid)
        #jobs.update_job_status(jid, str(start))
        #set inital outcomes count
        animal_outcomes_of_day = 0

        #x values: list of dates
        x_values_to_plot = []

        #y values: list of integer numbers of outcomes per date
        y_values_to_plot = []

        start_date = datetime.datetime.strptime(start, "%m-%d-%Y")
        end_date = datetime.datetime.strptime(end, '%m-%d-%Y')

        #format to check for full day, rather than specific time??????????
        for key in rd1.keys():
            #jobs.update_job_status(jid, 'you have entered the for loop')
            key_time_temp = str(rd1.hget(key, 'Date_of_Entry'))[1:]
            #jobs.update_job_status(jid, str(key_time_temp))
            #key_time_temp = key_time_temp.replace("/","-")

            #jobs.update_job_status(jid, str(key_time_temp))
            key_time = datetime.datetime.strptime(key_time_temp, "'%m-%d-%Y'")

            #jobs.update_job_status(jid, str(key_time_temp)) # -------------------
            #check for keys in date range
            if (start_date <= key_time and end_date >= key_time):
                #jobs.update_job_status(jid, 'this is entering 2nd if statement')
                #set specific date
                x = str(key_time)
                jobs.update_job_status(jid, str(x))  #  -----------
                #check if date is alread in x_values_to_plot
                if x not in x_values_to_plot:
                    jobs.update_job_status(
                        jid, 'this is entering 3rd if statement')
                    #if new date: add to list of x_values_to_plot
                    x_values_to_plot.append(x)

                    #check through db for each animal with matching Date_of_Entry
                    for i in range(rd1.dbsize()):

                        #will there be an issue with b formatting? should we use [1:]?
                        if (x == rd1.hget(i, 'Date_of_Entry')):

                            #increment animal_outcomes_of_day count
                            animal_outcomes_of_day = animal_outcomes_of_day + 1

                    #finalize count for the day
                    y = animal_outcomes_of_day

                    #add total count to list of y_values_to_plot
                    y_values_to_plot.append(y)

                #reset animal_outcomes_of_day count before moving to next day
                animal_outcomes_of_day = 0

        #plot line graph
        plt.scatter(x_values_to_plot, y_values_to_plot)
        #plt.show()
        plt.savefig('/outcomes_by_date.png')

        with open('/outcomes_by_date.png', 'rb') as f:
            img = f.read()

        rd.hset(f'job.{jid}', 'result', img)
        #rd.hset(jobid, 'image', img)

        #jobs.update_job_status(jid, 'complete')

    #analysis: plot total # of outcomes by type of animal in date range
    if (job_type == 'animal_type'):
        #jobs.update_job_status(jid, 'it has entered the for loop')
        animal_types = ['Bird', 'Cat', 'Dog', 'Livestock', 'Other']
        animal_counts = [0, 0, 0, 0, 0]

        for key in rd1.keys():
            #jobs.update_job_status(jid, str(key))#'it has entered the for loop')
            this_animal_type = str(rd1.hget(key, 'Animal_Type'))[1:]
            #jobs.update_job_status(jid, str(this_animal_type))
            if this_animal_type == "'Bird'":
                animal_counts[0] += 1
            elif this_animal_type == "'Cat'":
                animal_counts[1] += 1
            elif this_animal_type == "'Dog'":
                animal_counts[2] += 1
            elif this_animal_type == "'Livestock'":
                animal_counts[3] += 1
            elif this_animal_type == "'Other'":
                animal_counts[4] += 1
        #jobs.update_job_status(jid, str(animal_counts))
        plt.clf()
        plt.bar(animal_types, animal_counts, color='green')
        plt.xlabel('Animal Type')
        plt.ylabel('Frequency')
        plt.title('Outcomes by Animal Type')
        #plt.show()
        plt.savefig('/outcomes_by_animal_type.png')
        with open('/outcomes_by_animal_type.png', 'rb') as f:
            img = f.read()

        #rd.hset("job.{}".format(jid), 'image' img)
        rd.hset(f'job.{jid}', 'result', img)

        jobs.update_job_status(jid, 'complete')