コード例 #1
0
def zipcode_detail(request,slug):
    cache_key = "zipcode_detail slug=%s" % slug
    response = safe_get_cache(cache_key)
    
    if not response:
        place = get_object_or_404(ZipCode,id=slug)
        
        #title = "ZIP Code %s in %s, %s" % (place, place.county.long_name, place.county.state)
        if place.state:
            title = "ZIP Code %s, %s" % (place, place.state)
        else:
            title = "ZIP Code %s" % place

        response=render_to_response("places/place_detail.html",{
            'title':title,
            'place':place,
            'demographics':getattr(place.population_demographics,'__dict__',{}),
            'place_type':"zipcode"
        },context_instance=RequestContext(request))
        
        safe_set_cache(cache_key,response,604800)

        # It's likely that the user will go to the State's page from here (since it's linked
        # from the detail page). Call it right now to pre-cache it.
        if (not USING_DUMMY_CACHE) and (place.state):
            call_in_bg(state_detail,(None,place.state.slug))

    return response
コード例 #2
0
ファイル: safecache.py プロジェクト: mtigas/cs4970_capstone
 def render(self, context):
     try:
         expire_time = self.expire_time_var.resolve(context)
     except VariableDoesNotExist:
         raise TemplateSyntaxError('"safecache" tag got an unknkown variable: %r' % self.expire_time_var.var)
     try:
         expire_time = int(expire_time)
     except (ValueError, TypeError):
         raise TemplateSyntaxError('"safecache" tag got a non-integer timeout value: %r' % expire_time)
     
     # The cache name.
     cache_key = u':'.join([self.fragment_name])
     
     # The variables passed to the cache name.
     for var in self.vary_on:
         try:
             v = force_unicode(resolve_variable(var, context))
         except:
             v = "None"
         cache_key = "%s:%s=%s" % (cache_key,force_unicode(var),v)
     
     # Now work with the cache.
     try:
         value = safe_get_cache(cache_key)
     except:
         value = None
     if value is None:
         value = self.nodelist.render(context)
         safe_set_cache(cache_key, value, expire_time)
     return value
コード例 #3
0
ファイル: views.py プロジェクト: mtigas/cs4970_capstone
def threedee_test(request):
    cache_key = "threedee_test"
    response = safe_get_cache(cache_key)

    if not response:
        County = get_model("places","county")
        State = get_model("places","state")
        
        mo=State.objects.get(abbr="MO")

        
        values = []
        for county in County.objects.filter(state=mo)[:35].iterator():
            if (not county.population_demographics) or (not county.population_demographics.total) or (not county.area)\
                or (not county.socioeco_data) or (not county.socioeco_data.per_capita_income) or (not county.crime_data)\
                or (not county.crime_data.violent_crime):
                    continue
            
            pop_density = float(county.population_demographics.total)/float(county.area.sq_mi)
            if pop_density is 0:
                continue
            
            values.append(
                (pop_density, float(county.socioeco_data.per_capita_income), float(county.crime_data.violent_crime))
            )
        fig = threed_bar_chart(values,"Population Density","Per-Capita Income", "Violent Crimes")
        canvas=FigureCanvas(fig)
        response=HttpResponse(content_type='image/png')
        canvas.print_png(response)

        safe_set_cache(cache_key,response,86400)
        
    return response
コード例 #4
0
ファイル: views.py プロジェクト: mtigas/cs4970_capstone
def scatterhist_test(request):
    cache_key = "scatterhist_test"
    response = safe_get_cache(cache_key)
    
    if not response:
        County = get_model("places","county")
        
        values = []
        for county in County.objects.order_by("?")[:100].iterator():
            if (not county.population_demographics) or (not county.population_demographics.total) \
                or (not county.socioeco_data) or (not county.socioeco_data.median_income) or (not county.crime_data)\
                or (not county.crime_data.violent_crime):
                    continue
            
            var_a = float(county.socioeco_data.median_income)
            var_b = float(county.crime_data.violent_crimes_per100k)
            
            if (var_a is 0) or (var_b is 0):
                continue
            
            values.append(
                (var_a, var_b)
            )
        
        fig = histogram(values,"Median Income","Crime Rate")
        canvas=FigureCanvas(fig)
        response=HttpResponse(content_type='image/png')
        canvas.print_png(response)
        
        safe_set_cache(cache_key,response,86400)
    
    return response
コード例 #5
0
ファイル: views.py プロジェクト: Goldenbarqs/cs4970_capstone
def state_detail(request,slug):
    cache_key = "state_detail slug=%s GET=%s" % (slug, request.GET)
    response = safe_get_cache(cache_key)
    
    if not response:
        place = get_object_or_404(State,slug=slug)
        
        response=render_to_response("places/state_detail.html",{
            'title':str(place.name),
            'place':place,
            'demographics':getattr(place.population_demographics,'__dict__',{}),
            'place_type':"state"
        },context_instance=RequestContext(request))
        
        safe_set_cache(cache_key,response,604800)

    return response
コード例 #6
0
def seed_next_random():
    """
    Generates a redirect view to a random Place object (State, ZipCode, or County)
    and caches it. Picking a random place is expensive on the DB and CPU since there
    are over 40000 objects that it picks from, which strains the DB (since it causes
    an iteration over the objects to select the ID).
    
    See random_place() below, for notes on usage.
    """
    response = None
    while not response:
        try:
            PlaceClass = rand_choice([State,ZipCode,County])
            
            # Cached list of all of the ID numbers for this place type.
            cache_key = "all_ids: %s" % (PlaceClass.__name__)
            all_ids = safe_get_cache(cache_key)
            if not all_ids:
                all_ids = PlaceClass.objects.only('id').order_by().values_list('pk') # [(0,),(1,),...]
                all_ids = map(lambda x: x[0], all_ids) # pull ID out of tuples for a "regular" list
                safe_set_cache(cache_key,all_ids,604800)
            
            rand_id = rand_choice(all_ids)
            
            if PlaceClass.__name__ == "County":
                place = PlaceClass.objects.get(pk=rand_id)
                url = reverse("places:county_detail",args=(place.state.abbr.lower(),urlencode(place.name.lower())),current_app="places")
                call_in_bg(county_detail, (None, place.state.abbr.lower(),urlencode(place.name.lower())))
            elif PlaceClass.__name__ == "State":
                place = PlaceClass.objects.only('slug').get(pk=rand_id)
                url = reverse("places:state_detail",args=(place.slug,),current_app="places")
                call_in_bg(state_detail, (None, place.slug))
            else:
                place = PlaceClass.objects.only('slug').get(pk=rand_id)
                url = reverse("places:zipcode_detail",args=(place.slug,),current_app="places")
                call_in_bg(zipcode_detail, (None, place.slug))
            response = HttpResponseRedirect(url)
        except:
            from traceback import print_exc
            print_exc()
            response = None
    safe_set_cache("random_place",response,604800)
    
    return response
コード例 #7
0
ファイル: views.py プロジェクト: mtigas/cs4970_capstone
def boxplot_test(request):
    cache_key = "boxplot_test"
    response = safe_get_cache(cache_key)

    if not response:
        CrimeData = get_model("demographics","crimedata")
        State = get_model("places","state")
        mo=State.objects.get(abbr="MO")

        data = CrimeData.objects.filter(place_type__name="county",place_id__in=mo.counties).exclude(assault__gt=200).values_list('assault','murder','rape')
        
        fig = boxplot(zip(*data),("Assault","Murder","Rape"))
        canvas=FigureCanvas(fig)
        response=HttpResponse(content_type='image/png')
        canvas.print_png(response)

        safe_set_cache(cache_key,response,86400)
        
    return response
コード例 #8
0
ファイル: views.py プロジェクト: Goldenbarqs/cs4970_capstone
def random_place(request):
    """
    If a random place is in the cache, use it and return that to the user.
    If not, generate one right now.
    
    Before returning to the user, queue up a background task that generates
    the next random place, to save DB/CPU usage when responding to user. (Prevents
    this view from locking up while Django picks a suitable random object.)
    """
    cache_key = "random_place"
    response = safe_get_cache(cache_key)
    
    if not response:
        response = seed_next_random()
    
    # Pre-generate the next random location.
    if not USING_DUMMY_CACHE:
        call_in_bg(seed_next_random)
    
    return response
コード例 #9
0
ファイル: views.py プロジェクト: mtigas/cs4970_capstone
def county_detail(request,state_abbr,name):
    cache_key = "county_detail state_abbr=%s name=%s" % (state_abbr, name)
    response = safe_get_cache(cache_key)
    
    if not response:
        place = get_object_or_404(County,state__abbr__iexact=state_abbr,name__iexact=name)
        
        title = u"%s, %s" % (place.long_name, place.state)
        
        response=render_to_response("places/place_detail.html",{
            'title':title,
            'place':place,
            'demographics':getattr(place.population_demographics,'__dict__',{}),
            'socioeco_data':getattr(place.socioeco_data,'__dict__',{}),
            'crime_data':getattr(place.crime_data,'__dict__',{}),
            'place_type':'county'
        },context_instance=RequestContext(request))
        
        safe_set_cache(cache_key,response,86400)
    
    return response
コード例 #10
0
ファイル: views.py プロジェクト: mtigas/cs4970_capstone
def scatterplot_test(request):
    cache_key = "scatterplot_test"
    response = safe_get_cache(cache_key)

    if not response:
        State = get_model("places","state")
        
        values = []
        for state in State.objects.iterator():
            if (not state.population_demographics) or (not state.population_demographics.total) or (not state.area):
                continue
            
            pop_density = float(state.population_demographics.total)/float(state.area.sq_mi)
            
            # get rid of screwy outliers for the presentation demo
            if pop_density > 2000:
                continue
            if state.crime_data.violent_crime > 100000:
                continue
                        
            var_x = pop_density
            var_y = state.crime_data.violent_crime
            
            if (var_x is 0) or (var_y is 0):
                continue
            
            values.append(
                (var_x, var_y)
            )
        
        fig = scatterplot(values,"Population Density","Violent Crimes")
        canvas=FigureCanvas(fig)
        response=HttpResponse(content_type='image/png')
        canvas.print_png(response)

        safe_set_cache(cache_key,response,86400)
        
    return response
コード例 #11
0
ファイル: views.py プロジェクト: mtigas/cs4970_capstone
def random_place(request):
    """
    If a random place is in the cache, use it and return that to the user.
    If not, generate one right now.
    
    Before returning to the user, queue up a background task that generates
    the next random place, to save DB/CPU usage when responding to user. (Prevents
    this view from locking up while Django picks a suitable random object.)
    """
    response = None
    while not response:
        try:
            PlaceClass = rand_choice([State,County])
            
            # Cached list of all of the ID numbers for this place type.
            cache_key = "all_ids: %s" % (PlaceClass.__name__)
            all_ids = safe_get_cache(cache_key)
            if not all_ids:
                all_ids = PlaceClass.objects.only('id').order_by().values_list('pk') # [(0,),(1,),...]
                all_ids = map(lambda x: x[0], all_ids) # pull ID out of tuples for a "regular" list
                safe_set_cache(cache_key,all_ids,604800)
            
            rand_id = rand_choice(all_ids)
            
            if PlaceClass.__name__ == "County":
                place = PlaceClass.objects.get(pk=rand_id)
                url = reverse("places:county_detail",args=(place.state.abbr.lower(),urlencode(place.name.lower())),current_app="places")
            else:
                place = PlaceClass.objects.only('slug').get(pk=rand_id)
                url = reverse("places:state_detail",args=(place.slug,),current_app="places")
            response = HttpResponseRedirect(url)
        except:
            from traceback import print_exc
            print_exc()
            response = None
    return response