def chooseActivity(request): if request.method=='POST': #OK this is super not the way to do this, but oh well #also, may end up trying to add an activity and not be able to #super confusing probably, not at all the right way to do things pvalues=request.POST.copy() if not request.POST['activity']: if len(request.POST['add_activity']): newActivity=Activity(name=request.POST['add_activity']) newActivity.save(request) pvalues['activity']=newActivity.id aform=ActivityChooseForm(pvalues, request=request) if aform.is_valid(): aRating=aform.save(commit=False) aRating.preDateTime=datetime.datetime.now() aRating.save(request) rform=ActivityRatingForm(instance=aRating) pk=aRating.id redirectURL='/activity/'+str(pk)+'/rate/' return redirect(redirectURL) else: return render(request, 'activity/choose.html', {'aform':aform}) aform=ActivityChooseForm(request=request) return render(request, 'activity/choose.html',{'aform':aform})
def activity(r, u='', action='', group=''): timestamp = datetime.now().strftime('%Y%m%d%H%M%S') act = Activity(believer=u, group=group, timestamp=timestamp, action=action, ipaddress=IP(r), source='web', category='track') act.save(True) return 'OK'
def FromPSToTS(request, id_number): try: project = Object.objects.get(id=int(id_number)) except ObjectDoesNotExist: return HttpResponse('Об’єкт не існує.<br>Спробуйте інший id.') if request.method == 'POST': form = FromPStoTSForm(request.POST) if form.is_valid(): cd = form.cleaned_data act = Activity(time_stamp=dt.now(), aim = project, type='Видача предметів з Постійного зберігання на Тимчасове зберігання', actor=Custom.myUser.objects.get(username=request.user.username)) act.save() project.save() for (k, v) in cd.items(): if k=='material': v = unicode(v[1:-1].replace('u\'', '').replace('\'', '')) attr_assign = AttributeAssignment(attr_name=k, attr_value=v, attr_label=form.fields[k].label, event_initiator=act, aim=project) attr_assign.save() return HttpResponseRedirect('/') else: return render(request, 'AddOnTs.html', {'form': form, 'errors': form.errors}) else: ps_code = get_attrib_assigns('Приймання на постійне зберігання', project, 'PS_code') inventory_number = get_attrib_assigns('Інвентарний облік', project, 'inventory_number') data = {'name': project.name, 'is_fragment': project.is_fragment, 'amount': project.amount, 'date_creation': project.date_creation, 'place_of_creation': project.place_of_creation, 'author': project.author, 'technique': project.technique, 'material': project.material.decode('unicode-escape').split(', '), 'size': project.size, 'description': project.description, 'note': project.note, 'condition': project.condition, 'condition_descr': project.condition_descr, 'PS_code': ps_code, 'inventory_number': inventory_number, } form = FromPStoTSForm(initial=data) return render(request, 'AddOnTs.html', {'form': form, 'label': 'Видати об’єкт з ПЗ на ТЗ'})
def WritingOff(request, id_number): try: project = Object.objects.get(id=int(id_number)) except ObjectDoesNotExist: return HttpResponse('Об’єкт не існує.<br>Спробуйте інший id.') if request.method == 'POST': form = WritingOffForm(request.POST) if form.is_valid(): cd = form.cleaned_data act = Activity(time_stamp=dt.now(), aim = project, type='Списання', actor=Custom.myUser.objects.get(username=request.user.username)) act.save() project.save() for (k, v) in cd.items(): if k=='material': v = unicode(v[1:-1].replace('u\'', '').replace('\'', '')) attr_assign = AttributeAssignment(attr_name=k, attr_value=v, attr_label=form.fields[k].label, event_initiator=act, aim=project) attr_assign.save() return HttpResponseRedirect('/') else: return render(request, 'AddOnTs.html', {'form': form, 'errors': form.errors}) else: ps_code = get_attrib_assigns('Приймання на постійне зберігання', project, 'PS_code') inventory_number = get_attrib_assigns('Інвентарний облік', project, 'inventory_number') spec_inventory_numb = get_attrib_assigns('Спеціальний інвентарний облік', project, 'spec_inventory_numb') ts_code = get_attrib_assigns('Приймання на тимчасове зберігання', project, 'TS_code') data = {'name': project.name, 'is_fragment': project.is_fragment, 'amount': project.amount, 'note': project.note, 'PS_code': ps_code, 'inventory_number': inventory_number, 'spec_inventory_numb': spec_inventory_numb, 'TS_code': ts_code, } form = WritingOffForm(initial=data) return render(request, 'AddOnTs.html', {'form': form, 'label': 'Списати об’єкт'})
def fund(row): ''' A funding of a new individual Takes in a list of a row in CSV.''' port_indi = Port_Indi() act = Activity() # Creating the new portfolio/individual port_indi.cash = row[2] port_indi.networth = row[2] port_indi.name = row[1] # Check to see if its an Individual or a Porfolio if row[0] == 'fund': port_indi.is_individual = False else: port_indi.is_individual = True #port_indi.last_quote = Quote() port_indi.last_activity = act port_indi.save() # Activity act = Activity() act.amount = row[2] act.act_type = "fund" act.port_indi1 = port_indi act.date = row[3].replace('-', '') act.save() # Referencing activity port_indi.last_activity = act port_indi.save() print str(port_indi) + ' HAS BEEN FUNDED'
def TempSave(request, id_number=0): try: project = Object.objects.get(id=int(id_number)) except ObjectDoesNotExist: if id_number != 0: return HttpResponse('Об’єкт не існує.<br>Спробуйте інший id.') else: project = Object(name='Новий') if request.method == 'POST': form = TempSaveForm(request.POST, request.FILES) if form.is_valid(): cd = form.cleaned_data act = Activity(time_stamp=dt.now(), aim=project, type='Приймання на тимчасове зберігання', actor=Custom.myUser.objects.get(username=request.user.username)) act.save() project.reason = cd['reason'] project.save() for (k, v) in cd.items(): if k=='material': v = unicode(v[1:-1].replace('u\'', '').replace('\'', '')) attr_assign = AttributeAssignment(attr_name=k, attr_value=v, attr_label=form.fields[k].label, event_initiator=act, aim=project) attr_assign.save() return HttpResponseRedirect('/') else: return render(request, 'AddOnTs.html', {'form': form}) else: data = {'name': project.name, 'is_fragment': project.is_fragment, 'amount': project.amount, 'date_creation': project.date_creation, 'place_of_creation': project.place_of_creation, 'author': project.author, 'technique': project.technique, 'material': project.material.decode('unicode-escape').split(', '), 'size': project.size, 'condition': project.condition, 'condition_descr': project.condition_descr, 'description': project.description, 'price': project.price, 'note': project.note} form = TempSaveForm(initial=data) return render(request, 'AddOnTs.html', {'form': form, 'label': 'Прийняти об’єкт на ТЗ'})
def chooseActivity(request): if request.method == 'POST': #OK this is super not the way to do this, but oh well #also, may end up trying to add an activity and not be able to #super confusing probably, not at all the right way to do things pvalues = request.POST.copy() if not request.POST['activity']: if len(request.POST['add_activity']): newActivity = Activity(name=request.POST['add_activity']) newActivity.save(request) pvalues['activity'] = newActivity.id aform = ActivityChooseForm(pvalues, request=request) if aform.is_valid(): aRating = aform.save(commit=False) aRating.preDateTime = datetime.datetime.now() aRating.save(request) rform = ActivityRatingForm(instance=aRating) pk = aRating.id redirectURL = '/activity/' + str(pk) + '/rate/' return redirect(redirectURL) else: return render(request, 'activity/choose.html', {'aform': aform}) aform = ActivityChooseForm(request=request) return render(request, 'activity/choose.html', {'aform': aform})
def createNewActivity(request): title = request.POST['title'] host = request.POST['host'] undertake = request.POST['undertake'] time = request.POST['time'] area = request.POST['area'] place = request.POST['place'] tel = request.POST['tel'] email = request.POST['email'] brief = request.POST['brief'] detail = request.POST['detail'] number = int(request.POST['number']) c_id = request.POST['c_id'] club = Club.objects.get(id=c_id) today = str(date.today().year)+'-'+str(date.today().month)+'-'+str(date.today().day) #basic information information = activityInfo() information.title = title information.host = host information.undertake = undertake information.time = time information.area = area information.place = place information.tel = tel information.email = email information.number = number information.save() #host club host = hostClub() host.HC_club = club host.save() #record record = recordInfo() record.save() #create new activity new_activity = Activity() new_activity.information = information new_activity.club = host new_activity.school = club.school new_activity.record = record new_activity.brief_intro = brief new_activity.detail_intro = detail form = uploadFileForm(request.POST, request.FILES) if form.is_valid(): new_activity.image = request.FILES['image'] new_activity.safe_file = request.FILES['safe_file'] new_activity.save() createGlobalNews(club.id,new_activity.id,'3') return HttpResponse('1')
def rateCivi(request): civi_id = request.POST.get('civi_id', '') rating = request.POST.get('rating', '') account = Account.objects.get(user=request.user) c = Civi.objects.get(id=civi_id) try: prev_act = Activity.objects.get(civi=c, account=account) except Activity.DoesNotExist: prev_act = None try: activity_data = { 'account': account, 'thread': c.thread, 'civi': c, } if rating == "vneg": c.votes_vneg = c.votes_vneg + 1 vote_val = 'vote_vneg' elif rating == "neg": c.votes_neg = c.votes_neg + 1 vote_val = 'vote_neg' elif rating == "neutral": c.votes_neutral = c.votes_neutral + 1 vote_val = 'vote_neutral' elif rating == "pos": c.votes_pos = c.votes_pos + 1 vote_val = 'vote_pos' elif rating == "vpos": # c.votes_vpos = c.votes_vpos + 1 vote_val = 'vote_vpos' activity_data['activity_type'] = vote_val c.save() if prev_act: prev_act.activity_type = vote_val prev_act.save() data = { 'civi_id':prev_act.civi.id, 'activity_type': prev_act.activity_type, 'c_type': prev_act.civi.c_type } else: act = Activity(**activity_data) act.save() data = { 'civi_id':act.civi.id, 'activity_type': act.activity_type, 'c_type': act.civi.c_type } return JsonResponse({'data' : data}) except Exception as e: return HttpResponseServerError(reason=str(e))
def auto_checkout(): active_checkins = Checkin.checkins.active() for checkin in active_checkins: auto_checkout_activity = Activity() auto_checkout_activity = checkin.checkin_activity auto_checkout_activity.time = datetime.datetime.now() auto_checkout_activity.save() checkin.checkout_activity = auto_checkout_activity checkin.save()
def public_act(request): ret_data = {} errors = [] if request.method == 'POST': if 'user' in request.session: theme_act = request.POST.get('theme_act', '') if not theme_act: errors.append('theme not exist') class_act = request.POST.get('class_act', '') date_act = request.POST.get('date_act', '') time_act = request.POST.get('time_act', '') num_act = request.POST.get('num_act', '') address_act = request.POST.get('address_act', '') detail_act = request.POST.get('detail_act', '') username = request.session['user'] date_time = date_act + " " + time_act userid = User.objects.get(name=username).id now = datetime.datetime.fromtimestamp( time.mktime(time.strptime(date_time, r"%Y/%m/%d %H:%M:%S"))) datess = str(now) print datess try: a = int(num_act) except Exception: ret_data["ret"] = 'no int' return HttpResponse(json.dumps(ret_data), content_type='application/json') print "now is " + str(datess) if len(errors) > 0: ret_data['ret'] = 'no theme' elif not num_act: ret_data['ret'] = 'no people_count' else: pub_data = Activity(category=class_act, theme=theme_act, begin_datatime=datess, people_count=num_act, details=detail_act, submit_peopleId=userid, location=address_act, joined_peopleId=userid) #total=len(Activity.objects.all())+1 pub_data.istimeout = 'n' pub_data.save() total = pub_data.id u = User.objects.get(id=userid) if u.uncompleted_id == '': u.uncompleted_id = str(total) else: u.uncompleted_id += (',' + str(total)) u.save() ret_data['ret'] = 'ok' else: ret_data['ret'] = 'failed' else: ret_data['ret'] = 'failed' return HttpResponse(json.dumps(ret_data), content_type='application/json')
def checkout(modeladmin, request, queryset): for checkin in queryset: activity = Activity() activity.time = datetime.datetime.now() activity.carrier = checkin.checkin_activity.carrier activity.client = checkin.checkin_activity.client activity.save() checkin.checkout_activity = activity checkin.save()
def post(self): data = request.json person = Persons.query.filter_by(name=data['person']).first() activity = Activity(name=data['name'], person = person) activity.save() response = { 'person':activity.person.name, 'name': activity.name } return response
def Passport(request, id_number): try: project = Object.objects.get(id=int(id_number)) except ObjectDoesNotExist: if id_number != '0': return HttpResponse('Об’єкт не існує.<br>Спробуйте інший id.') else: project = Object(name='Новий') if request.method == 'POST': form = PassportForm(request.POST) if form.is_valid(): cd = form.cleaned_data project.save() act = Activity(time_stamp=dt.now(), aim = project, type='Науково-уніфікований паспорт', actor=Custom.myUser.objects.get(username=request.user.username)) act.save() for (k, v) in cd.items(): if k=='material': v = unicode(v[1:-1].replace('u\'', '').replace('\'', '')) attr_assign = AttributeAssignment(attr_name=k, attr_value=v, attr_label=form.fields[k].label, event_initiator=act, aim=project) attr_assign.save() return HttpResponseRedirect('/') else: return render(request, 'AddOnTs.html', {'form': form, 'errors': form.errors}) else: collection = get_attrib_assigns('Інвентарний облік', project, 'collection') ps_code = get_attrib_assigns('Приймання на постійне зберігання', project, 'PS_code') inventory_number = get_attrib_assigns('Інвентарний облік', project, 'inventory_number') spec_inventory_numb = get_attrib_assigns('Спеціальний інвентарний облік', project, 'spec_inventory_numb') old_inventory_numbers = get_attrib_assigns('Інвентарний облік' or 'Приймання на постійне зберігання',project, 'old_registered_marks') date_place_creation = ' '.join([project.date_creation, project.place_of_creation]) date_place_detection = ' '.join([project.date_detection, project.place_detection]) date_place_existence = ' '.join([project.date_existence, project.place_existence]) source = get_attrib_assigns('Приймання на постійне зберігання', project, 'source') classify = get_attrib_assigns('Інвентарний облік', project, 'classify') typology = get_attrib_assigns('Інвентарний облік', project, 'typology') metals = get_attrib_assigns('Спеціальний інвентарний облік', project, 'metals') stones = get_attrib_assigns('Спеціальний інвентарний облік', project, 'stones') bibliography = get_attrib_assigns('Інвентарний облік', project, 'bibliography') data = {'collection': collection, 'PS_code': ps_code, 'inventory_number': inventory_number, 'spec_inventory_numb': spec_inventory_numb, 'old_inventory_numbers': old_inventory_numbers, 'identifier': project.identifier, 'storage': project.storage, 'name': project.name, 'author': project.author, 'date_place_creation': date_place_creation, 'date_place_detection': date_place_detection, 'date_place_existence': date_place_existence, 'source': source, 'way_of_found': project.way_of_found, 'link_on_doc': project.link_on_doc, 'classify': classify, 'typology': typology, 'amount': project.amount, 'size': project.size, 'material': project.material.decode('unicode-escape').split(', '), 'technique': project.technique, 'metals': metals, 'stones': stones, 'description': project.description, 'condition': project.condition, 'condition_descr': project.condition_descr, 'recomm_for_restauration': project.recomm_for_restauration, 'transport_possibility': project.transport_possibility, 'price': project.price, 'bibliography': bibliography} form = PassportForm(initial=data) return render(request, 'AddOnTs.html', {'form': form, 'label': 'Створити науково-уніфікований паспорт об’єкта'})
def public_act(request): ret_data={} errors =[] if request.method=='POST': if 'user' in request.session: theme_act = request.POST.get('theme_act','') if not theme_act: errors.append('theme not exist') class_act = request.POST.get('class_act','') date_act = request.POST.get('date_act','') time_act = request.POST.get('time_act','') num_act = request.POST.get('num_act','') address_act = request.POST.get('address_act','') detail_act = request.POST.get('detail_act','') username = request.session['user'] date_time = date_act + " " + time_act userid = User.objects.get(name=username).id now = datetime.datetime.fromtimestamp(time.mktime(time. strptime(date_time, r"%Y/%m/%d %H:%M:%S"))) datess = str(now) print datess try: a = int(num_act) except Exception: ret_data["ret"] = 'no int' return HttpResponse(json.dumps(ret_data), content_type='application/json') print "now is " +str(datess) if len(errors) > 0: ret_data['ret'] = 'no theme' elif not num_act: ret_data['ret'] = 'no people_count' else: pub_data = Activity(category = class_act, theme = theme_act, begin_datatime = datess, people_count = num_act, details = detail_act, submit_peopleId = userid, location=address_act,joined_peopleId=userid) #total=len(Activity.objects.all())+1 pub_data.istimeout = 'n' pub_data.save() total = pub_data.id u=User.objects.get(id=userid) if u.uncompleted_id=='': u.uncompleted_id=str(total) else: u.uncompleted_id+=(','+str(total)) u.save() ret_data['ret'] = 'ok' else: ret_data['ret'] = 'failed' else: ret_data['ret'] = 'failed' return HttpResponse(json.dumps(ret_data), content_type='application/json')
def post(self, request, format=None): date = request.DATA.get('date') try: activity = Activity.objects.get(name=request.DATA.get('activity')) except Activity.DoesNotExist: activity = Activity(name=request.DATA.get('activity'), average_price=0) activity.save() p = Process(date=request.DATA.get('date'), activity=activity, average_price=0) p.save() consumer_list = json.loads(request.DATA.get('list')) user_to_be_saved = [] total = 0 try: for num, i in enumerate(consumer_list): name = i.get('name') prepay = i.get('prepay') consume = i.get('consume') #check name user = User.objects.get(name=name) p.participants.add(user) #user money user.remain += prepay - consume user_to_be_saved.append(user) total += consume #send email except: print sys.exc_info() p.delete() return Response(status=404) #caculate the average price of process p.average_price =total/(num +1) #caculate the average price of activity if p.average_price == 0: activity.average_price = p.average_price else: activity.average_price = (p.average_price + activity.average_price)/2 p.save() for i in user_to_be_saved: i.save() return Response({"detail":"success"} ,status=200)
def rateCivi(request): civi_id = request.POST.get('civi_id', '') rating = request.POST.get('rating', '') account = Account.objects.get(user=request.user) voted_civi = Civi.objects.get(id=civi_id) if voted_civi.thread.is_draft: return HttpResponseServerError(reason=str("Cannot vote on a civi that is in a thread still in draft mode")) try: prev_act = Activity.objects.get(civi=voted_civi, account=account) except Activity.DoesNotExist: prev_act = None activity_data = { 'account': account, 'thread': voted_civi.thread, 'civi': voted_civi, } activity_vote_key = 'votes_{}'.format(rating) vote_val = 'vote_{}'.format(rating) # F object doesn't cause losing data in case of race setattr(voted_civi, activity_vote_key, F(activity_vote_key) + 1) voted_civi.save() if prev_act: prev_act.activity_type = vote_val prev_act.save() act = prev_act else: act = Activity(**activity_data) act.save() data = { 'civi_id': act.civi.id, 'activity_type': act.activity_type, 'c_type': act.civi.c_type } return JsonResponse({'data': data})
def AddOnSpecInventorySave(request, id_number): try: project = Object.objects.get(id=int(id_number)) except ObjectDoesNotExist: if id_number != '0': return HttpResponse('Об’єкт не існує.<br>Спробуйте інший id.') else: project = Object(name='Новий') if request.method == 'POST': form = SpecInventorySaveForm(request.POST) if form.is_valid(): cd = form.cleaned_data act = Activity(time_stamp=dt.now(), aim = project, type='Спеціальний інвентарний облік', actor=Custom.myUser.objects.get(username=request.user.username)) act.save() project.save() for (k, v) in cd.items(): if k=='material': v = unicode(v[1:-1].replace('u\'', '').replace('\'', '')) attr_assign = AttributeAssignment(attr_name=k, attr_value=v, attr_label=form.fields[k].label, event_initiator=act, aim=project) attr_assign.save() return HttpResponseRedirect('/') else: return render(request, 'AddOnTs.html', {'form': form, 'errors': form.errors}) else: ps_code = get_attrib_assigns('Приймання на постійне зберігання', project, 'PS_code') inventory_number = get_attrib_assigns('Інвентарний облік', project, 'inventory_number') mat_person_in_charge = get_attrib_assigns('Інвентарний облік' or 'Приймання на постійне зберігання', project, 'mat_person_in_charge') data = {'name': project.name, 'is_fragment': project.is_fragment, 'amount': project.amount, 'author': project.author, 'date_creation': project.date_creation, 'place_of_creation': project.place_of_creation, 'size': project.size, 'description': project.description, 'condition': project.condition, 'condition_descr': project.condition_descr, 'recomm_for_restauration': project.recomm_for_restauration, 'note': project.note, 'price': project.price, 'PS_code': ps_code, 'inventory_number': inventory_number, 'link_on_doc': project.link_on_doc, 'mat_person_in_charge': mat_person_in_charge, 'storage': project.storage} form = SpecInventorySaveForm(initial=data) return render(request, 'AddOnTs.html', {'form': form, 'label': 'Взяти об’єкт на спеціальний інвентарний облік'})
def TempRet(request, id_number=0): try: project = Object.objects.get(id=int(id_number)) except ObjectDoesNotExist: if id_number != 0: return HttpResponse('Об’єкт не існує.<br>Спробуйте інший id.') else: return HttpResponseRedirect('prepare') if project.attributeassignment_set.filter(approval=False, aim=project).exists(): return HttpResponse('У цього об’єкта є незатвердженi подiї.') if request.method == 'POST': form = TempRetForm(request.POST) if form.is_valid(): cd = form.cleaned_data act = Activity(time_stamp=dt.now(), aim = project, type='Повернення з тимчасового зберiгання', actor=Custom.myUser.objects.get(username=request.user.username)) act.save() for (k, v) in cd.items(): if k=='material': v = unicode(v[1:-1].replace('u\'', '').replace('\'', '')) attr_assign = AttributeAssignment(attr_name=k, attr_value=v, attr_label=form.fields[k].label, event_initiator=act, aim=project) attr_assign.save() return HttpResponseRedirect('/') else: return render(request, 'AddOnTs.html', {'form': form, 'errors': form.errors}) else: reason = str(get_attrib_assigns('Приймання на тимчасове зберігання', project, 'reason')) data = {'name': project.name, 'is_fragment': project.is_fragment, 'amount': project.amount, 'date_creation': project.date_creation, 'place_of_creation': project.place_of_creation, 'author': project.author, 'technique': project.technique, 'material': project.material.decode('unicode-escape').split(', '), 'size': project.size, 'description': project.description, 'condition': project.condition, 'condition_descr': project.condition_descr, 'term_back': project.term_back, 'reason': reason, 'side_1': project.side_1, 'side_2': project.side_2, 'price': project.price, 'note': project.note } form = TempRetForm(initial=data) return render(request, 'AddOnTs.html', {'form': form, 'label': 'Повернути об’єкт з ТЗ'})
def updateDB(acts): for act in acts: try: title = act['title'] type = act['type'] price = getPrice(act) date = act['date'] time = act['time'] long = act['long'] == '1' url = act['url'] except KeyError: print "Activity", title, "is not complete" continue try: newAct = Activity.objects.get(title=title, date=date, time=time) newAct.type = type newAct.price = price newAct.long = long newAct.url = url except Activity.DoesNotExist: newAct = Activity(title=title, type=type, price=price, date=date, time=time, long=long, url=url) newAct.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()
def buy(row): ''' buying into a portfolio or company. Takes in a list of a row in CSV. buy,fund_1,MMM,233780,2005-01-20 buy,ind_2,fund_2,6671,2005-01-18 ''' buying_port = Port_Indi.objects.get(name=row[1]) # Activity act = Activity() act.amount = row[3] act.act_type = "buy" act.port_indi1 = buying_port act.date = row[4].replace('-', '') # Stakehold stake = StakeHold() stake.last_modified = row[4].replace('-', '') stake.fund = buying_port tickers = yahooDataRetriever.get_top_500_tickers(ticker_file) # check whether buying company or portfolio if row[2] not in tickers: # Buying Portfolio purchase_port = Port_Indi.objects.get(name=row[2]) act.port_indi2 = purchase_port stake.fund2 = purchase_port # Check cash amount #if cash >= float(act.amount): #purchase_port.c # Calculate Percentage # Update other investors percenages # Calculate networths else: # Buying Company act.company = Company.objects.get(ticker=row[2]) stake.company = Company.objects.get(ticker=row[2]) stakes = list(StakeHold.objects.filter(fund=buying_port,company=stake.company)) print len(stakes) cash = act.port_indi1.cash print row[4].replace('-', '') print stake.company hist_data = list(Historical_Data.objects.filter(date=row[4].replace('-', ''), company=Company.objects.get(ticker=row[2]))) hist_data_record = hist_data[0] # check if stakehold exists already if stakes == []: #stake.save() #stake.shares = float(row[3]) stake.shares = float(row[3]) / hist_data_record.closing else: stake = StakeHold.objects.get(fund=buying_port,company=stake.company) #stake.shares = float(row[3]) stake.shares += float(row[3]) / hist_data_record.closing # Checking funds if cash >= float(act.amount): stake.save() act.save() buying_port.cash = cash - int(act.amount) buying_port.save() print "## BUY TRANSACTION COMPLETED" else: print "### INSUFFICIENT FUNDS: TRANSACTION NOT COMPLETED"
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()