def login(request): ''' authentication :param request: :return: ''' if request.method == 'GET': code = request.GET.get("code", None) # request for the access_token and refresh token print "code: %s"%code r = getToken(code) if r: # get user info userInfo = getUserInfo(r['access_token'],r['openid']) discounts = Discount_Info.objects.filter(lang=0).order_by('-dis_id')[:15] ozdiscounts = Discount_Info.objects.filter(lang=1).order_by('-dis_id')[:15] rates = Rate.objects.all() # store user info is_exist = Visitor.objects.filter(openid=userInfo['openid']) if not is_exist: user = Visitor() # 存在即更新 else: user = is_exist[0] for key in user.__dict__: if key in userInfo: setattr(user, key, userInfo[key]) user.save() return render_to_response('index.html', dict(data=userInfo, discounts=discounts, rates=rates, ozdiscounts=ozdiscounts) ) # else: response = HttpResponse(u"认证失败") return response
def index(request): ''' render index :param request: :return: ''' discounts = Discount_Info.objects.filter(lang=0,status=1).order_by('-dis_id')[:15] ha = {u'province': u'', u'openid': u'oa6cGt4PrUC9BSWuK09IvehmgcNUaaaa', u'headimgurl': u'http://wx.qlogo.cn/mmopen/PiajxSqBRaELwKcgGMFpnGn4WNVzPicUMoOuI0foZ06uozNK2pC4Bu96VibfyRDzvrkMY2kdSPEMcj97McG2J4a5A/0', u'language': u'zh_CN', u'city': u'', u'country': '\xe4\xb8\xad\xe5\x9b\xbd', u'sex': 1, u'privilege': [], u'nickname': '\xe5\xb0\x8f\xe5\x93\x92'} is_exist = Visitor.objects.filter(openid=ha['openid']) banner = Banner.objects.filter()[0] if not is_exist: user = Visitor() # 存在即更新 else: user = is_exist[0] for key in user.__dict__: if key in ha: setattr(user, key, ha[key]) user.save() rates = Rate.objects.all() url = MEDIA_URL+os.path.basename(banner.headimgurl.url) # return render_to_response('index.html', dict(data=ha,rates=rates , discounts=discounts)) return render_to_response('cleaning.html', dict(url=url))
def incoming_click(request,category): '''Every page load creates a new visitor object. This visitor object is updated with a random site and offerset (combination of 2 offers), then redirected to the page template.''' #To do: Use publisher component to send messages to any consumer... SendMessage(visitor) v = Visitor() #get params (v.referer, v.user_agent, v.domain, v.category) = (request.META.get('HTTP_REFERER'), request.META.get('HTTP_USER_AGENT'), request.META.get('SERVER_NAME'), category, ) #get url params (v.adsource, v.account, v.ad, v.agegroup,v.image, v.channel, v.testing, v.safeview) = (request.GET.get('adsource','missing'), request.GET.get('account','missing'), request.GET.get('ad','missing'), request.GET.get('agegroup','missing'), request.GET.get('image','missing'), request.GET.get('channel','missing'), request.GET.get('testing','missing'), request.GET.get('safeview','missing'), ) if category not in category_list: v.category = 'Error' v.save() return HttpResponse("Category %s was not found" % category) site = get_site(category) v.site = site v.offerset_id, offer_list = get_offerset(site) v.save() name,link = _get_display_name_and_link(v,offer_list) return render_to_response('%s/%s' % (v.category,site.page1_template), locals())
def create_visit_request(user, visiting_point, company, data): try: visitor = user.visitor except User.DoesNotExist: visitor = Visitor(user=user, phone=data['phone']) visitor.save() vr = VisitRequest(company=company, visitor=visitor, visiting_point=visiting_point) vr.save() for k,v in data.items(): if k[0:3]=='sf_': va = VisitAttributes(visit_request=vr, attr_id = int(k[3:]), val=v) va.save() return vr
def create_visit_request(user, visiting_point, company, data): try: visitor = user.visitor except User.DoesNotExist: visitor = Visitor(user=user, phone=data['phone']) visitor.save() vr = VisitRequest(company=company, visitor=visitor, visiting_point=visiting_point) vr.save() for k, v in data.items(): if k[0:3] == 'sf_': va = VisitAttributes(visit_request=vr, attr_id=int(k[3:]), val=v) va.save() return vr
def incoming_click(request, category): '''Every page load creates a new visitor object. This visitor object is updated with a random site and offerset (combination of 2 offers), then redirected to the page template.''' #To do: Use publisher component to send messages to any consumer... SendMessage(visitor) v = Visitor() #get params (v.referer, v.user_agent, v.domain, v.category) = ( request.META.get('HTTP_REFERER'), request.META.get('HTTP_USER_AGENT'), request.META.get('SERVER_NAME'), category, ) #get url params (v.adsource, v.account, v.ad, v.agegroup, v.image, v.channel, v.testing, v.safeview) = ( request.GET.get('adsource', 'missing'), request.GET.get('account', 'missing'), request.GET.get('ad', 'missing'), request.GET.get('agegroup', 'missing'), request.GET.get('image', 'missing'), request.GET.get('channel', 'missing'), request.GET.get('testing', 'missing'), request.GET.get('safeview', 'missing'), ) if category not in category_list: v.category = 'Error' v.save() return HttpResponse("Category %s was not found" % category) site = get_site(category) v.site = site v.offerset_id, offer_list = get_offerset(site) v.save() name, link = _get_display_name_and_link(v, offer_list) return render_to_response('%s/%s' % (v.category, site.page1_template), locals())
def process_request(self, request): # Don't process AJAX request if request.is_ajax(): return # Create some useful variables: ip_address = utils.get_ip(request) user_agent = unicode(request.META.get('HTTP_USER_AGENT', '')[:255], errors='ignore') # Retrieve untracked user agents from cache ua_key = '_tracking_untracked_uas' untracked = cache.get(ua_key) if untracked is None: log.info("Updating untracked user agent cache") untracked = UntrackedUserAgent.objects.all() cache.set(ua_key, untracked, 3600) # See if the user agent is not supposed to be tracked. ACTIVITY = True for ua in untracked: # if the keyword is found in the user agent, stop tracking if user_agent.find(ua.keyword) != -1: if not ua.activity: log.debug('Not tracking UA "%s" because of keyword: %s' % (user_agent, ua.keyword)) return else: ACTIVITY = False if hasattr(request, 'session') and request.session.session_key: # Use the current session key if we can session_key = request.session.session_key else: # Otherwise just fake a session key session_key = '%s:%s' % (ip_address, user_agent) session_key = session_key[:40] # Ensure that the request.path does not begin with any of the prefixes for prefix in self.prefixes: if request.path.startswith(prefix): log.debug('Not tracking request to: %s' % request.path) return # If we get here, the URL needs to be tracked # determine what time it is now = datetime.now() attrs = { 'session_key': session_key, 'ip_address': ip_address } # For some reason, Vistors.objects.get_or_create is not working here try: visitor = Visitor.objects.get(**attrs) except Visitor.DoesNotExist: # See if there's a visitor with the same IP and user agent # within the last 5 minutes cutoff = now - timedelta(minutes=5) visitors = Visitor.objects.filter( ip_address=ip_address, user_agent=user_agent, last_update__gte=cutoff ) if len(visitors): visitor = visitors[0] visitor.session_key = session_key log.debug('Using existing visitor for IP %s / UA %s: %s' % (ip_address, user_agent, visitor.id)) else: # It's probably safe to assume that the visitor is brand new visitor = Visitor(**attrs) log.debug('Created a new visitor: %s' % attrs) except: return # Determine whether or not the user is logged in user = request.user if isinstance(user, AnonymousUser): user = None # Update the tracking information: visitor.user = user visitor.user_agent = user_agent # If the visitor record is new, or the visitor hasn't been here for # at least an hour, update their referrer URL. one_hour_ago = now - timedelta(hours=1) if not visitor.last_update or visitor.last_update <= one_hour_ago: visitor.referrer = utils.u_clean(request.META.get('HTTP_REFERER', 'unknown')[:255]) # Reset the number of pages they've been to visitor.page_views = 0 visitor.session_start = now visitor.url = request.path visitor.last_update = now # Tracking #time_on_site = 0 #if visitor.start_time: # time_on_site = (now - visitor.start_time).seconds #print("time_on_site %s (%s)" % (time_on_site, visitor.time_on_site)) #visitor.time_on_site = time_on_site SAVE_ACTIVITY = False if TRACK_ACTIVITIES and ACTIVITY: # Match against `path_info` to not include the SCRIPT_NAME path = request.path_info.lstrip('/') for url in TRACK_IGNORE_URLS: if url.match(path): break else: SAVE_ACTIVITY = True visitor.page_views += 1 else: path = request.path_info.lstrip('/') for url in TRACK_IGNORE_URLS: if url.match(path): break else: visitor.page_views += 1 try: visitor.save() except DatabaseError: log.error('There was a problem saving visitor information:\n%s\n\n%s' % (traceback.format_exc(), locals())) if SAVE_ACTIVITY: activity = Activity(visitor=visitor, url=request.path, view_time=now) activity.save()
def setUp(self): visitor = Visitor(name='New Visitor', email='*****@*****.**', phone='+5511991437851', custom_id='283900739202') visitor.save()
def process_request(self, request): # Don't process AJAX request if request.is_ajax(): return # Create some useful variables: ip_address = utils.get_ip(request) user_agent = unicode(request.META.get('HTTP_USER_AGENT', '')[:255], errors='ignore') # Retrieve untracked user agents from cache ua_key = '_tracking_untracked_uas' untracked = cache.get(ua_key) if untracked is None: log.info("Updating untracked user agent cache") untracked = UntrackedUserAgent.objects.all() cache.set(ua_key, untracked, 3600) # See if the user agent is not supposed to be tracked. ACTIVITY = True for ua in untracked: # if the keyword is found in the user agent, stop tracking if user_agent.find(ua.keyword) != -1: if not ua.activity: log.debug('Not tracking UA "%s" because of keyword: %s' % (user_agent, ua.keyword)) return else: ACTIVITY = False if hasattr(request, 'session') and request.session.session_key: # Use the current session key if we can session_key = request.session.session_key else: # Otherwise just fake a session key session_key = '%s:%s' % (ip_address, user_agent) session_key = session_key[:40] # Ensure that the request.path does not begin with any of the prefixes for prefix in self.prefixes: if request.path.startswith(prefix): log.debug('Not tracking request to: %s' % request.path) return # If we get here, the URL needs to be tracked # determine what time it is now = datetime.now() attrs = {'session_key': session_key, 'ip_address': ip_address} # For some reason, Vistors.objects.get_or_create is not working here try: visitor = Visitor.objects.get(**attrs) except Visitor.DoesNotExist: # See if there's a visitor with the same IP and user agent # within the last 5 minutes cutoff = now - timedelta(minutes=5) visitors = Visitor.objects.filter(ip_address=ip_address, user_agent=user_agent, last_update__gte=cutoff) if len(visitors): visitor = visitors[0] visitor.session_key = session_key log.debug('Using existing visitor for IP %s / UA %s: %s' % (ip_address, user_agent, visitor.id)) else: # It's probably safe to assume that the visitor is brand new visitor = Visitor(**attrs) log.debug('Created a new visitor: %s' % attrs) except: return # Determine whether or not the user is logged in user = request.user if isinstance(user, AnonymousUser): user = None # Update the tracking information: visitor.user = user visitor.user_agent = user_agent # If the visitor record is new, or the visitor hasn't been here for # at least an hour, update their referrer URL. one_hour_ago = now - timedelta(hours=1) if not visitor.last_update or visitor.last_update <= one_hour_ago: visitor.referrer = utils.u_clean( request.META.get('HTTP_REFERER', 'unknown')[:255]) # Reset the number of pages they've been to visitor.page_views = 0 visitor.session_start = now visitor.url = request.path visitor.last_update = now # Tracking #time_on_site = 0 #if visitor.start_time: # time_on_site = (now - visitor.start_time).seconds #print("time_on_site %s (%s)" % (time_on_site, visitor.time_on_site)) #visitor.time_on_site = time_on_site SAVE_ACTIVITY = False if TRACK_ACTIVITIES and ACTIVITY: # Match against `path_info` to not include the SCRIPT_NAME path = request.path_info.lstrip('/') for url in TRACK_IGNORE_URLS: if url.match(path): break else: SAVE_ACTIVITY = True visitor.page_views += 1 else: path = request.path_info.lstrip('/') for url in TRACK_IGNORE_URLS: if url.match(path): break else: visitor.page_views += 1 try: visitor.save() except DatabaseError: log.error( 'There was a problem saving visitor information:\n%s\n\n%s' % (traceback.format_exc(), locals())) if SAVE_ACTIVITY: activity = Activity(visitor=visitor, url=request.path, view_time=now) activity.save()