Пример #1
0
def main(request):
    user = getUser(request)
    
    meal_on = True
    if isWeekend():
        meal_on = False
    
    """Get expiration"""
    pacific = timezone('US/Pacific')
    pa_time = datetime.now(pacific)
    pa = pa_time.strftime('%d,%m,%Y,%B,%A')
    date_array = pa.split(',')
    
    day_as_num = int(date_array[0])
    month_as_num = int(date_array[1]) - 1
    year = date_array[2]
    
    """Get meal"""
    id=None
    store=None
    selected_recipes, item_dict, total = getMeal('sanfrancisco', store, id)
    
    url = None
    r_name = None
    r_attr = None
    if selected_recipes:
        r = selected_recipes[0]
        r_name = r.name
        r_attr = r.attribution
        image_key = str(r.image.file.blobstore_info.key())
        url = images.get_serving_url(image_key)
    else:
        meal_on = False
    
    if request.method == 'POST': 
        prospect = ProspectForm(request.POST) # A form bound to the POST data
        if prospect.is_valid():
            new_p = prospect.save()
            """Save location"""
            try:
                new_p.full_address = request.session['location']
            except KeyError:
                pass
            new_p.save()
            #logging.debug('New address: %s' % new_p.full_address)
            
            """Save referrer"""
            new_p.referrer = request.session['whereFrom']
            new_p.save()
            
            if 'referral' in request.GET:
                new_p.invite = request.GET.get('referral')
                new_p.save()
            
            return thanks_page(request, new_p)
    else:         
        prospect = ProspectForm()
    
    CITY_LIST = ['San Francisco', 'Other']
    
    request.session['whereFrom'] = request.META.get('HTTP_REFERER', '')
    template = 'home/home_current.html'
    
    data = {'user':user, 'form':prospect, 'year':year, 'date_today':pa_time, 'rname':r_name,
            'rattr':r_attr, 'image':url, 'dn':day_as_num, 'mn':month_as_num, 'city_list':CITY_LIST, 
            'meal_on':meal_on}
    
    return render_to_response(template, data,context_instance=RequestContext(request))
Пример #2
0
def api_order(request, city):
    #Check cache 
    from google.appengine.api import memcache
    
    pacific = timezone('US/Pacific')
    now = datetime.now(pacific)
    tomorrow = datetime(now.year, now.month, now.day, 23, 59, 59, tzinfo=pacific)
    
    td = tomorrow-now
    expire = td.seconds
    
    order = memcache.get("latest_order-1")
    #if current_order(order):
    if False:
        return HttpResponse(order,content_type = 'application/javascript; charset=utf8')
    else:
        user = getUser(request)
        id = None
               
        """Get Meal"""
        selected_recipes, item_dict, total = getMeal(city, id)
        if selected_recipes:
            r = selected_recipes[0]
        else:
            #get earliest from previous day
            selected_recipes, item_dict, total = getLatestMeal(city,id)
            r = selected_recipes[0]
        
        servings = r.serv
        cooktime = r.cooktime
        name = r.name
        
        """Get Directions """
        #Check for direction sections - looks for <u> tag
        directions = r.dirfull
        dirfull_dict = format_directions(directions)
        
        """Get Service fee """
        service_fee = '3.99'
        if user:
            subscribed = isSubscriber(user)
            if subscribed:
                service_fee = '0.00'
            
        """Get Ingredients """
        #Check for direction sections - looks for <u> tag
        ingredients = r.ingrfull
        ingrfull_dict = format_ingredients(ingredients)
       
        
        """Get all stores"""
        from django.core import serializers
        data = serializers.serialize("json", Store.objects.filter(city='San Francisco', active=True),fields=('store_name','street1','city','state','postal_code','lat','lng'))
        sdata = simplejson.loads(data)
        stores = []
        for s in sdata:
            f = s['fields']
            store_dict = {}
            store_dict['storeid'] = s['pk']
            store_dict['name'] = f['store_name']
            store_dict['street'] = f['street1']
            store_dict['city'] = f['city']
            store_dict['state'] = f['state']
            store_dict['state'] = f['state'] 
            store_dict['country'] = 'United States'
            store_dict['zip'] = f['postal_code']
            store_dict['lat'] = f['lat']
            store_dict['lng'] = f['lng']
            
            stores.append(store_dict)
        
        """Get image"""
        image_key = str(r.image.file.blobstore_info.key())
        url_x = images.get_serving_url(image_key)
        url = '%s=s320'% url_x
        
        s1 = Store.objects.all()[2]
        pickuptime = getTime(s1)
        
        code = 200
        
        ps_all = get_currentday_promo('sanfrancisco')
        if ps_all:
            ps = ps_all[0]
        else:
            ps_all = get_latest_promo('sanfrancisco')
            ps = ps_all[0]
        
        #Sample format "2011-11-15T09:58:52-0800"
        
        promo_date_x = ps.date
        pacific = timezone('US/Pacific')
        promo_date = promo_date_x.replace(tzinfo=pacific)
        
        #Need to update
        dt = datetime(year=promo_date.year, month=promo_date.month, day=promo_date.day, hour=16, minute=30, tzinfo=pacific)
        endtime = dt.strftime('%Y-%m-%dT%H:%M:%S%z')
        
        #Used for testing
        #now = datetime.now(pacific)
        #dt = datetime(year=now.year, month=now.month, day=now.day, hour=16, minute=30, tzinfo=pacific)
        #endtime = dt.strftime('%Y-%m-%dT%H:%M:%S%z')
        
        """Get items for meal"""
        item_array = []
        itemfull_dict = {}
        for k,v in item_dict.items():
            items = {}
            items['name'] = k
            items['price'] = "%.2f" % v
            items['selected'] = inExclude(k)
            
            item_array.append(items)
        
        new_dict = nonexcluded_item_dict(item_dict)
        item_dict, total = get_items_latest_price(new_dict, ps)
        
        price = total/r.serv
        price_per = ("%.2f" % price)
        
        total_x = ("%.2f" % total)
        
        pe = PromoEmail.objects.get(promoschedule=ps)
        summary = pe.meal_summary
        
        id = str(pe.id)
        
        meal_dict = {'image': url, 'cooktime': cooktime,'dirfull':dirfull_dict, 'endtime': endtime,
                      'ingrfull':ingrfull_dict, 'item_selections': item_array, 'name':name, 'promoid':ps.id,
                      'pickuptime':pickuptime, 'price_per':price_per, 'servings':servings, 
                      'stores':stores, 'summary':summary, 'total':total_x, 'id':id, 'service_fee':service_fee} 
        
        data = {'code':code, 'meal':meal_dict}
        order = simplejson.dumps(data, cls=MyJSONEncoder)
        
        memcache.delete("latest_order-1")
        if not memcache.add("latest_order-1", order):
            logging.error("Memcache set failed.")
        
    return HttpResponse(
        order,
        content_type = 'application/javascript; charset=utf8'
    )