Esempio n. 1
0
def detailed_results(request):
    # The function for our detailed results page
    # Matches the house id with the selected house and adds the data to the dictionary
    # Creates and saves a graph
    c = {}
    house_id=request.POST.get("house_id")
    if not house_id:
        return render(request, 'search/error.html', c)
    with open(HOUSE_PATH+"/attributes.csv", "r") as f:
        header=f.readline()
        reader=csv.reader(f)
        for row in reader:
            if int(row[0])==int(house_id):
                c["current_lat"]=row[5]
                c["current_long"]=row[6]
                c["current_bedroom"]=row[3]
                c["current_bathroom"]=row[4]
                c["current_price"]=row[2]
                c["current_address"]=row[1]
                c["current_house_id"]=house_id
                c["current_link"] = row[8]
                break
    c['current_distance'] = request.POST.get('distance', 1200)
    data=[]
    all_crimes={}
    line_styles=[".r-", ".b-", ".g-", ".y-"]
    # The following code both saves a graph using matlibplot and stores chart data to use in charts
    graph_data_raw = []
    c['pie_data']=[]
    for j in DATABASE_CATEGORIES:
        all_crimes[j]={}
        with open(HOUSE_PATH+"/{}/{}.csv".format(house_id.strip(),j), "r") as f:
            header=f.readline()
            reader=csv.reader(f)
            for row in reader:
                date=row[0]
                month_year=date[:7]
                all_crimes[j][month_year]=all_crimes[j].get(month_year, 0)+1
        t_labels=list(all_crimes[j].keys())
        t_labels.sort()
        t=range(len(t_labels))
        s=[all_crimes[j][k] for k in t_labels]
        # Stores the pie data for crime
        c['pie_data'].append((j, sum(s)))
        if len(t)>15:
            step=(len(t)//15)+1
            for k in range(len(t_labels)):
                if k%step!=0:
                    t_labels[k]=""
        # Stores the graph data for crime
        graph_data_raw.append((j,t_labels,s))
        plt.xticks(t, t_labels, rotation=30)    
        plt.plot(t, s, line_styles.pop(), label =j)
    plt.xlabel("Date YYYY-MM")
    plt.ylabel("Number of crimes")
    plt.title("Crime within {}m of this property".format(c["current_distance"]))
    plt.legend()
    plt.grid(True)
    plt.savefig(HOUSE_PATH+"/{}/historical_crime.png".format(house_id.strip()))
    plt.clf()
    #c["crime_graph"]=HOUSE_PATH+"/{}/historical_crime.png".format(house_id.strip())

    # Changes graph_data_raw into correct format
    crime_list = []
    for date in graph_data_raw[0][1]:
        crime_list.append([date])
    for i in range(len(graph_data_raw)):
        crime_data = graph_data_raw[i][2]
        for j in range(len(crime_data)):
            crime_list[j].append(crime_data[j])
    c['graph_data'] = crime_list
    # Passes in the database categories for the pie chart
    c['database_cat'] = DATABASE_CATEGORIES
    # Gets the category selected, not selecting is the equivalent of no filter for category
    current_cat = request.POST.get('cat')
    if not current_cat:
        current_cat = ""
    # Passes the yelp categories to use in the form
    c['categories'] = ["restaurants", "active",
     "arts", "education", "health", "nightlife", "shopping"]
    distance = float(c["current_distance"])
    units = request.POST.get("distance_type")
    # Corrects distance for units and limit (Yelp limit is 40000)
    if units == "miles":
        distance *= 1609.34
    if distance > 40000:
        distance = 40000
    c["current_term"] =request.POST.get("term", "food")
    page = request.POST.get('page',1)
    c['current_page'] = page
    # Stores and passes in the Yelp results 
    c['results'], total = Yelp.yelp_search((c["current_lat"], c["current_long"]),
     distance, c['current_term'], category_filter = current_cat, offset = (int(page)-1)*20)
    # Calculates the number of pages the user can request
    c['pages'] = list(range(1,math.ceil(total/20)))
    
    return render(request, 'search/detailed_results.html', c)