def save_checkins(): for cdata in iterate_file("checkin", shortcircuit=False): checkin = Checkin() checkin.business_id = cdata['business_id'] for day in range(7): for hour in range(24): number = int(cdata['checkin_info'].get("%s-%s" % (hour, day), 0)) if day is 0: checkin.sunday_count += number elif day is 1: checkin.monday_count += number elif day is 2: checkin.tuesday_count += number elif day is 3: checkin.wednesday_count += number elif day is 4: checkin.thursday_count += number elif day is 5: checkin.friday_count += number elif day is 6: checkin.saturday_count += number try: checkin.save() except InternalError: print "i dont care" pass
def checkin (request): messages = [] if request.method == 'POST': form = ScanForm(request.POST) if form.is_valid(): data = form.cleaned_data idnum = data["scan"] if len(Person.objects.filter(id=idnum)) != 0: person = Person.objects.get(id=idnum) checkins = Checkin.objects.filter(person=person, completed=False) if len(checkins) == 0: messages.append("Successfully checked in " + person.first_name + " " + person.last_name) new_checkin = Checkin(person=person, checkin=datetime.now(), checkout=datetime.now()) new_checkin.save() else: for obj in checkins: obj.checkout = datetime.now() obj.completed = True obj.save() person.hours += float((obj.checkout - obj.checkin).total_seconds()) / 3600 person.save() messages.append("Successfully checked out " + person.first_name + " " + person.last_name) form = ScanForm() return render(request, "scanner/checkin.html", {"form": form, "messages": messages})
def check_out(student_id, class_id): """Check_out student from a class""" try: student = Student.get(Student.id == student_id) except Exception: cprint('Student Not Found', 'red') return try: class_ = Class_.get(Class_.id == class_id) except Exception: cprint('Class Not Found', 'red') return # Prevent checking out if class is not in session if class_.session == 1: cprint( "Warning! Class in session. End class to check out student", 'red', 'on_grey') cprint("Force checkout? y/N", 'cyan') ans = raw_input() if ans.lower() == 'y': cprint("Reason for checking out {}".format( student.student_name), 'cyan') text = raw_input() log = Checkout_Log.create( student_name=student.student_name, student_id=student.id, reason=text) log.save() check_out = Checkin.update(status=0).where( (Checkin.student_id == student_id) and (Checkin.class__id == class_id)) check_out.execute() # Set the student's check_in status to false qry = Student.update(checked_in=0).where(Student.id == student_id) qry.execute() cprint("Checked out {} from {}.\n\tReason: {}".format( student.student_name, class_.class_name, log.reason), 'cyan', 'on_grey') else: # Update checked in status to false check_out = Checkin.update(status=0).where( (Checkin.student_id == student_id)and (Checkin.class__id == class_id)) check_out.execute() # Set the student's check_in status to false qry = Student.update(checked_in=0).where(Student.id == student_id) qry.execute() cprint("Checked out {} from {} class".format( student.student_name, class_.class_name), 'green', 'on_grey')
def log_end(class_id): """End class session""" try: class_instance = Class_.get(Class_.id == class_id) except Exception: cprint('Student Not Found', 'red') return end = time.time() if not class_instance.session: cprint("{} is not in session".format( class_instance.class_name), 'red') else: # Update end time with current time update_end_time = Class_.update( end_time=end).where(Class_.id == class_id) update_end_time.execute() # Set class session to closed closed = Class_.update(session=0).where(Class_.id == class_id) closed.execute() cprint("{0} class has ended".format( class_instance.class_name), 'green', 'on_grey') # Checkout all students in the class for entry in Checkin.select().where(Checkin.class__id == class_id, Checkin.status == 1): # set student checked_in 0 qry = entry.student.update(checked_in=0) qry.execute() # s_qry.execute() cprint("Checked out all students", 'green', 'on_grey')
def check_in(student_id, class_id): """Checkin student to a class""" try: student = Student.get(Student.id == student_id) except Exception: cprint('Student Id Not Found', 'red') return try: class_ = Class_.get(Class_.id == class_id) except Exception: cprint('Class Not Found', 'red') return if student.checked_in: cprint("{} is already checked in".format( student.student_name), 'red', 'on_grey') elif not class_.session: cprint("{} is not in session".format( class_.class_name), 'red', 'on_grey') else: # Add a check in entry to check_ins table check_in = Checkin.create( student=student, class_=class_, status=1) check_in.save() # Set the student's check_in status to true qry = Student.update(checked_in=1).where(Student.id == student_id) qry.execute() cprint("Checked in {} to {} class".format( student.student_name, class_.class_name), 'green', 'on_grey')
def checkin(): if not request.data == '': data = unicode(request.data).__str__().split(';') else: if len(request.form.keys()) == 1: data = unicode(request.form.keys()[0]).__str__().split(';') else: data = '' print data if not len(data) == 3 or not (data[0] == 'm' or data[0] == 'c'): return unicode('invalid') name = 'carter' if data[0] == 'm': name = 'mike' user = User.query.filter_by(name=name).first() if user is None: return unicode('invalid') try: lat = float(data[1]) lon = float(data[2]) except ValueError: return unicode('invalid') checkin = Checkin(latitude=lat, longitude=lon, timestamp=datetime.datetime.now(), user=user) db.session.add(checkin) db.session.commit() return unicode('got;it')
def checkin(request, id): p = Place.objects.filter(id=id) u = request.user errors = [] c_id = '' c_time = '' u_id = '' u_name = '' if not isinstance(u, User): errors.append('user not login') if not errors: u_id = u.id u_name = u.username if p: p= p[0] c = Checkin(place=p,user=u) c_id = c.id c_time = c.time.hour c.save() else: errors.append('no such place') result = dict( response = dict( meta = dict(), errors = errors, status = 'success' if not errors else 'fail', data = dict( checkin = dict( id = c_id, time = c_time, user = dict( id = u_id, username = u_name, ) ) ) ) ) return HttpResponse(json.dumps(result))
def checkin(request): user = request.user ticker = request.GET['symbol'] checkInType = request.GET['type'] symbolName = request.GET.get('symbolName','') comment = request.GET.get('comment','') checkin = Checkin(user=user, created=datetime.utcnow(), checkInType=checkInType, ticker=ticker, comment=comment, twitter=request.GET.get('sharetwitter',0), facebook=request.GET.get('sharefacebook',0), symbolName=symbolName, symbolType=request.GET.get('symbolType', ''), symbolExchange=request.GET.get('exchange', '')) checkin.save() # 2 points per checkin for now user.points = user.points + 2; user.save() if request.GET.get('sharefacebook', 0) and not user.id == 1: fbmsg = "%s %s" % (CHECKINTYPE[checkInType], ticker) if symbolName: fbmsg = "%s (%s)" % (fbmsg,symbolName) if comment: fbmsg = '%s "%s"' % (fbmsg,comment) put_wall_post(request,fbmsg) thirtydaysago = datetime.today() - timedelta(days=30) jsonresponse = { 'checkInsForTicker': Checkin.objects.filter(user=user).filter(ticker__iexact=ticker).filter(checkInType__iexact=checkInType).count(), 'otherCheckInsForTicker': Checkin.objects.exclude(user=user).filter(ticker__exact=ticker).filter(checkInType__iexact=checkInType).filter(created__gte=thirtydaysago).count(), 'otherTickerInterest': Checkin.objects.exclude(user=user).filter(ticker__exact=ticker).filter(created__gte=thirtydaysago).count(), 'pointsEarned': 2, 'totalPoints': user.points, 'badgeID': 0 } return HttpResponse(simplejson.dumps(jsonresponse), content_type='application/json')
def students_log(class_id): """List all students that have ever attended a class""" try: log = Checkin.select().distinct().where(Checkin.class__id == class_id) except Exception: cprint("Student not found", 'red') return table = [] headers = ["Id", "Student"] for item in log: table.append([item.student.id, item.student.student_name]) print(tabulate(table, headers, tablefmt="fancy_grid"))
def post(self): r = request.get_json(force=True) checkinBatch = r[10:len(r) - 6].strip().replace("\n", "").split('}, {') for singleCheckin in checkinBatch: json_data = json.loads('{' + singleCheckin + '}') try: checkin = Checkin(date=json_data['date'], business_id=json_data['business_id']) except Exception as e: return (str(e)) postgres.session.add(checkin) postgres.session.commit() return {}
def list_classes(): """List all classes""" cprint("List of all classes:", 'cyan', 'on_grey') table = [] headers = ["Id", "Name", "In Session", "Students"] for class_ in Class_.select(): if class_.session: n = Checkin.select().where((Checkin.class__id == class_.id) and (Checkin.status == 1)) count = n.count() else: count = "" table.append([class_.id, class_.class_name, class_.session, count]) print(tabulate(table, headers, tablefmt="fancy_grid"))
def list_students(): """List all students""" # cprint(figlet_format('List of all students:'), # 'green', attrs=['bold']) cprint("List of all students:", 'cyan', 'on_grey') table = [] headers = ["Id", "Name", "Checked In", "Class"] for student in Student.select(): if student.checked_in: sc = Checkin.select().where(Checkin.student_id == student.id and Checkin.status == 1).get() c = sc.class_.class_name else: c = "" table.append( [student.id, student.student_name, student.checked_in, c]) print(tabulate(table, headers, tablefmt="fancy_grid"))
def classes_log(student_id): """List all classes a student has ever attended""" try: log = Checkin.select().distinct().where(Checkin.student_id == student_id) except Exception: cprint("Student not found", 'red') return table = [] added = [] headers = ["Id", "class"] for item in log: if item.id not in added: table.append([item.class_.id, item.class_.class_name]) else: pass added.append(item.id) print(tabulate(table, headers, tablefmt="fancy_grid"))
def post(self): logging.error(dir(self.auth)) if not self.auth.user: return Response('Error: authenticate first') place_key_name = self.request.form.get('place_key_name') l = Location.all().filter('osm =', place_key_name).fetch(1) if not l: l = Location(osm = place_key_name) l.put() else: l = l[0] c = Checkin(user=self.auth.user, location=l) osmpoi = OSMPOI.get_by_key_name(place_key_name) place_name = osmpoi.name if place_name: c.place_name = place_name else: c.place_key_name = osmpoi.key().name() c.user_name = self.auth.user.username c.put() return Response('Success %s, %s' % (self.auth.user, place_key_name) )
def post(self): logging.error(dir(self.auth)) if not self.auth.user: return Response('Error: authenticate first') place_key_name = self.request.form.get('place_key_name') l = Location.all().filter('osm =', place_key_name).fetch(1) if not l: l = Location(osm=place_key_name) l.put() else: l = l[0] c = Checkin(user=self.auth.user, location=l) osmpoi = OSMPOI.get_by_key_name(place_key_name) place_name = osmpoi.name if place_name: c.place_name = place_name else: c.place_key_name = osmpoi.key().name() c.user_name = self.auth.user.username c.put() return Response('Success %s, %s' % (self.auth.user, place_key_name))
def student_checkin(student, lesson, abnormal=None): try: checkin = Checkin.objects.get(lesson=lesson, student=student) except ObjectDoesNotExist: checkin = Checkin(lesson=lesson, student=student) # checkindata.seatid = seatid nowtime = datetime.datetime.now() if checkin.status > 10: # ASK return {'error': 101, 'message': '学生已经请假'} if not checkin.time: checkin.time = nowtime if lesson.status == LESSON_STATUS_CHECKIN: if checkin.status == CHECKIN_STATUS_NORMAL: checkin.status = CHECKIN_STATUS_SUCCESS elif lesson.status == LESSON_STATUS_CHECKIN_ADD: if checkin.status == CHECKIN_STATUS_NORMAL: checkin.status = CHECKIN_STATUS_LATE elif checkin.status == CHECKIN_STATUS_EARLY: checkin.status = CHECKIN_STATUS_SUCCESS elif checkin.status == CHECKIN_STATUS_LATEEARLY: checkin.status = CHECKIN_STATUS_LATE elif lesson.status == LESSON_STATUS_CHECKIN_AGAIN: if checkin.laststatus == CHECKIN_STATUS_NORMAL: return {'error': 101, 'message': '再签模式不能新签入'} elif checkin.laststatus == CHECKIN_STATUS_LATE: checkin.status = CHECKIN_STATUS_LATE elif checkin.laststatus == CHECKIN_STATUS_EARLY: checkin.status = CHECKIN_STATUS_SUCCESS elif checkin.laststatus == CHECKIN_STATUS_LATEEARLY: checkin.status = CHECKIN_STATUS_LATE elif checkin.status == CHECKIN_STATUS_NORMAL: checkin.status = CHECKIN_STATUS_SUCCESS if checkin.abnormal is None and abnormal is not None: checkin.abnormal = abnormal checkin.save() return {'error': 0, 'status': checkin.status, 'checkin_id': checkin.id}
def experiment_checkin(request): form = ExperimentCheckinForm(request.POST) if form.is_valid(): data = form.cleaned_data experiment = Experiment.objects.get(key=data.get("experiment_key")) checkin = Checkin() checkin.experiment = experiment checkin.checkin_time = timezone.now() checkin.did_follow_instructions = data.get("did_follow_instructions") checkin.happiness = data.get("happy") checkin.stress = data.get("stress") checkin.productivity = data.get("productivity") checkin.leisure_time = data.get("leisure_time") checkin.app_version = data.get("app_version", "") day = (checkin.checkin_time.date() - experiment.start_time.date()).days + 1 checkin.save() result = dict(day=day) should_end, ended_early, restarted_stage = experiment.should_end_stage() if restarted_stage: result['restarted_stage'] = restarted_stage experiment.save() if should_end: result['new_stage'] = True result['ended_early'] = ended_early experiment.end_stage() experiment.save() inputs, outputs = experiment.get_stage_data(experiment.current_stage, always_get_median=True) result['stage_inputs'] = inputs result['stage_outputs'] = outputs result['target'] = experiment.get_daily_target(experiment.current_stage, len(result['stage_inputs']) - 1) result['current_stage'] = experiment.current_stage if not experiment.is_active: experiment.calculate_results() experiment.save() result['is_complete'] = True result['result_value'] = experiment.result_value result['result_confidence'] = experiment.result_confidence result['stage_results'] = experiment.stage_results return json_response(success=True, key=experiment.key, result=result) return json_response(success=False)
def changecheckinstatus(request, lessonid): lesson = Lesson.objects.get(id=lessonid) studentid = request.GET.get('studentid', default=False) or request.GET.get('pk') newstatus = request.GET.get('newstatus', default=False) or request.GET.get('value') try: student = Student.objects.get(studentid=studentid) except ObjectDoesNotExist: return HttpResponse(json.dumps({'error': 101, 'message': '未找到,请输入正确的学号'}), content_type="application/json") if not (has_course_permission(request.user, lesson.course) or request.user.has_perm('checkin_modify')): return HttpResponse(json.dumps({'error': 101, 'message': '没有权限'}), content_type="application/json") try: checkin = Checkin.objects.get(student=student, lesson=lesson) except ObjectDoesNotExist: if not Studentcourse.objects.filter(course=lesson.course, student=student).exists(): Studentcourse.objects.create(course=lesson.course, student=student) checkin = Checkin(student=student, lesson=lesson) """ 关闭请假不允许修改功能 if checkin.status > 10: # ASK return HttpResponse(json.dumps({'error': 101, 'message': '学生已经请假'}), content_type="application/json") """ if newstatus == 'newcheckin': data = student_checkin(student, lesson) elif newstatus == 'delete': checkin.status = CHECKIN_STATUS_NORMAL checkin.save() data = {'studentid': studentid, 'status': checkin.status} elif newstatus == 'late': checkin.status = CHECKIN_STATUS_LATE checkin.save() data = {'studentid': studentid, 'status': checkin.status} elif newstatus == 'success': checkin.status = CHECKIN_STATUS_SUCCESS checkin.save() data = {'studentid': studentid, 'status': checkin.status} elif newstatus == 'early': checkin.status = CHECKIN_STATUS_EARLY checkin.save() data = {'studentid': studentid, 'status': checkin.status} elif newstatus == 'lateearly': checkin.status = CHECKIN_STATUS_LATEEARLY checkin.save() data = {'studentid': studentid, 'status': checkin.status} elif newstatus == 'private_ask': checkin.status = CHECKIN_STATUS_PRIVATE_ASK checkin.save() data = {'studentid': studentid, 'status': checkin.status} elif newstatus == 'public_ask': checkin.status = CHECKIN_STATUS_PRIVATE_ASK checkin.save() data = {'studentid': studentid, 'status': checkin.status} elif newstatus == 'sick_ask': checkin.status = CHECKIN_STATUS_SICK_ASK checkin.save() data = {'studentid': studentid, 'status': checkin.status} elif newstatus.isdigit(): checkin.status = newstatus checkin.save() data = {'studentid': studentid, 'status': checkin.status} return HttpResponse(json.dumps(data), content_type="application/json")
def schedule(request): schedule=[] today = date.today() while today.weekday() >= 5 or ScheduleDay.objects.filter(date=today).count() > 0 and ScheduleDay.objects.get(date=today).day_off: today += timedelta(1) schedule_day = None if ScheduleDay.objects.filter(date=today).count() > 0: schedule_day = ScheduleDay.objects.get(date=today) else: done = False one_day = timedelta(1) today_dt = datetime.combine(today, time()) today_dt -= one_day new_date = today_dt.date() days_ellapsed = 0 day = 0 while not done: if new_date.weekday() < 5 and ScheduleDay.objects.filter(date=new_date).count() == 0: days_ellapsed += 1 elif new_date.weekday() < 5 and not ScheduleDay.objects.get(date=new_date).day_off: done = True day = (ScheduleDay.objects.get(date=new_date).day + days_ellapsed) % 7 new_dt = datetime.combine(new_date, time()) new_dt -= one_day new_date = new_dt.date() schedule_day = ScheduleDay(date=today, day_off=False, day=day, schedule="") schedule_day.save() print(schedule_day.day) if (schedule_day.schedule == "" schedule_day.schedule = master_schedule[schedule_day.day] s if len(schedule_day.period_set.all()) == 0: for i in range(len(schedule_day.schedule)): period = Period(day=schedule_day, period_number=i, period_letter=schedule_day.schedule[i:i + 1]) period.save() schedule.append([["Day " + str(schedule_day.day + 1)]]) for period in schedule_day.schedule: schedule.append([[period]]) return render(request, "scanner/schedule.html", {'schedule_table': schedule}) @not_login_required def checkin (request): messages = [] if request.method == 'POST': form = ScanForm(request.POST) if form.is_valid(): data = form.cleaned_data idnum = data["scan"] if len(Person.objects.filter(id=idnum)) != 0: person = Person.objects.get(id=idnum) checkins = Checkin.objects.filter(person=person, completed=False) if len(checkins) == 0: messages.append("Successfully checked in " + person.first_name + " " + person.last_name) new_checkin = Checkin(person=person, checkin=datetime.now(), checkout=datetime.now()) new_checkin.save() else: for obj in checkins: obj.checkout = datetime.now() obj.completed = True obj.save() person.hours += float((obj.checkout - obj.checkin).total_seconds()) / 3600 person.save() messages.append("Successfully checked out " + person.first_name + " " + person.last_name) form = ScanForm() return render(request, "scanner/checkin.html", {"form": form, "messages": messages}) @not_login_required def scan (request, idnum): idnum = int(idnum) if idnum < 10000 or idnum > 20000: return user(request, idnum) if idnum > 10000 and idnum < 20000: return checkout_item(request, idnum) return render(request, "scanner/item.html", {"idnum": idnum}) @not_login_required def user (request, idnum): if len(Person.objects.filter(id=idnum)) == 0: if request.method == 'POST': form = NewUserForm(request.POST) if form.is_valid(): person = form.save(commit=False) person.id = idnum person.save() else: form = NewUserForm() return render(request, "scanner/newuser.html", {"idnum": idnum, "form": form}) person = Person.objects.get(id=idnum) messages = [] if request.method == 'POST': form = ScanForm(request.POST) if form.is_valid(): if len(CheckoutItem.objects.filter(id=form.cleaned_data["scan"])) > 0: item = CheckoutItem.objects.get(id=form.cleaned_data["scan"]) if len(Checkout.objects.filter(person=person, item=item, checked_in=False)) > 0: for checkout in Checkout.objects.filter(person=person, item=item, checked_in=False): checkout.checked_in = True checkout.date_returned = datetime.now() checkout.save() messages.append(item.name + " successfully checked in.") else: new_checkout = Checkout(person=person, item=CheckoutItem.objects.get(id=form.cleaned_data["scan"]), date_checked_out=datetime.now() , date_due=datetime.now() + timedelta(CheckoutItem.objects.get(id=form.cleaned_data["scan"]).default_checkout_time)) new_checkout.save() messages.append(item.name + " successfully checked out.") else: messages.append("That item is not in the database.") form = ScanForm() return render(request, "scanner/user.html", {"person": person, "form": form, "checkouts": Checkout.objects.filter(person=person, checked_in=False), "messages": messages}) @not_login_required def checkout_item (request, idnum): if len(CheckoutItem.objects.filter(id=idnum)) == 0: if request.method == 'POST': form = NewItemForm(request.POST) if form.is_valid(): item = form.save(commit=False) item.id = idnum item.save() else: form = NewItemForm() return render(request, "scanner/newitem.html", {"idnum": idnum, "form": form}) else: form = NewItemForm() return render(request, "scanner/newitem.html", {"idnum": idnum, "form": form}) return render(request, "scanner/item.html", {"item": CheckoutItem.objects.get(id=idnum)}) @not_login_required def checkout(request, personid, itemid): return render(request, "scanner/item.html", {"item": CheckoutItem.objects.get(id=itemid)}) @login_required def admin(request): person = request.user.leadershipmember return render(request, "scanner/admin.html", {"person": person}) @not_login_required def admin_login(request): if request.method == 'POST': form = AdminLoginForm(request.POST) if form.is_valid(): data = form.cleaned_data username = data["id"] password = data["password"] user = authenticate(username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect(reverse("admin")) form = AdminLoginForm() return render(request, "scanner/admin_login.html", {"form": form}) @login_required def admin_add_leadership(request): if not request.user.leadershipmember.can_add_leadership_members: return HttpResponseRedirect(reverse("admin")) if request.method == 'POST': form = NewLeadershipMemberForm(request.POST) if form.is_valid(): data = form.cleaned_data person = Person.objects.get(id=data["id"]) if len(User.objects.filter(username=data["id"])) == 0: print(data["password"]) user = User.objects.create_user(data["id"], data["email"], data["password"]) user.save() user = User.objects.get(username=data["id"]) leadershipmember = LeadershipMember(first_name=person.first_name, last_name=person.last_name, id=person.id, hours=person.hours, periods=data["periods"], user=user) person.delete() leadershipmember.save() return HttpResponseRedirect(reverse("admin")) form = NewLeadershipMemberForm() return render(request, "scanner/admin_add_leadership.html", {"form": form}) @login_required def admin_change_permissions(request): if not request.user.leadershipmember.can_change_leadership_permissions: return HttpResponseRedirect(reverse("admin")) leadershipmembers = LeadershipMember.objects.exclude(id=request.user.leadershipmember.id) return render(request, "scanner/admin_change_permissions.html", {'leadershipmembers': leadershipmembers}) @login_required def admin_edit_info(request): if request.method == 'POST': form = LeadershipEditInfoForm(request.POST, instance=request.user.leadershipmember) if form.is_valid(): form.save() return HttpResponseRedirect(reverse("admin")) form = LeadershipEditInfoForm(instance=request.user.leadershipmember) return render(request, "scanner/admin_edit_info.html", {"form": form}) @login_required def admin_change_user_permissions(request, id): if not request.user.leadershipmember.can_change_leadership_permissions: return HttpResponseRedirect(reverse("admin")) if request.method == 'POST': form = ChangePermissionsForm(request.POST) if form.is_valid(): print("1") data = form.cleaned_data lm = LeadershipMember.objects.get(id=id) lm.can_add_leadership_members = data["can_add_leadership_members"] lm.can_change_leadership_permissions = data["can_change_leadership_permissions"] lm.save() return HttpResponseRedirect(reverse("admin change permissions")) person = request.user.leadershipmember form = ChangePermissionsForm(instance=LeadershipMember.objects.get(id=id)) return render(request, "scanner/admin_change_user_permissions.html", {"form": form, "person": person, "id": id})
def home(request): if request.method == 'POST': try: # capture JSON data, convert to dictionary jsonData = simplejson.loads(request.POST['checkin']) # check to see if the user already exists try: user = FoursquareUser.objects.get(userId = jsonData['user']['id']) # if not, then create him! except Exception: # we have to check since since the twitter field isn't always there try: twttr = jsonData['user']['contact']['twitter'], except: twttr = None, # make the user model user = FoursquareUser( userId = jsonData['user']['id'], firstName = jsonData['user']['firstName'], lastName = jsonData['user']['lastName'], photo = jsonData['user']['photo'], gender = jsonData['user']['gender'], homeCity = jsonData['user']['homeCity'], bio = jsonData['user']['bio'], twitter = twttr ) # save dat ish user.save() # check to see if the venue exists try: venue = Venue.objects.get(venueId = jsonData['venue']['id']) # if not, then create it! except Exception: # see if the contact stuff exists try: phn = jsonData['venue']['contact']['phone'] except: phn = None try: twttr = jsonData['venue']['contact']['twitter'] except: twttr = None # make the venue model venue = Venue( venueId = jsonData['venue']['id'], name = jsonData['venue']['name'], phone = phn, twitter = twttr, address = jsonData['venue']['location']['address'], lat = jsonData['venue']['location']['lat'], lng = jsonData['venue']['location']['lng'], postalCode = jsonData['venue']['location']['postalCode'], city = jsonData['venue']['location']['postalCode'], state = jsonData['venue']['location']['state'], country = jsonData['venue']['location']['country'], categoryId = jsonData['venue']['categories'][0]['id'], categoryName = jsonData['venue']['categories'][0]['name'], categoryPluralName = jsonData['venue']['categories'][0]['pluralName'], categoryShortName = jsonData['venue']['categories'][0]['shortName'], categoryIcon = jsonData['venue']['categories'][0]['icon'], categoryPrimary = jsonData['venue']['categories'][0]['primary'], statsCheckinsCount = jsonData['venue']['stats']['checkinsCount'], statsUsersCount = jsonData['venue']['stats']['usersCount'], statsTipsCount = jsonData['venue']['stats']['tipCount'], statsLikesCount = jsonData['venue']['likes']['count'], url = jsonData['venue']['url'] ) # save dat ish venue.save() checkin = Checkin( checkinId = jsonData['id'], createdAt = datetime.datetime.fromtimestamp(jsonData['createdAt']), timezone = jsonData['timeZone'], user = user, venue = venue ) checkin.save() # ping the netduino! c = pycurl.Curl() c.setopt(c.URL, "http://69.193.126.141:8080") c.perform() return HttpResponse("OK\r\n") except Exception as steve: return HttpResponseServerError("ERROR" + " " + steve.message + "\r\n") else: print "NOT POST!" return HttpResponseServerError("ERROR NOT POST")
def push(request): if request.method == 'POST': try: # capture JSON data, convert to dictionary jsonData = simplejson.loads(request.POST['checkin']) # ping the netduino right away r = ping.delay() # check to see if the user already exists try: user = FoursquareUser.objects.get(userId = jsonData['user']['id']) # if not, then create him! except Exception: # we have to check since since the twitter field isn't always there try: twttr = jsonData['user']['contact']['twitter'], except: twttr = None, # make the user model user = FoursquareUser( userId = jsonData['user']['id'], firstName = jsonData['user']['firstName'], lastName = jsonData['user']['lastName'], photo = jsonData['user']['photo'], gender = jsonData['user']['gender'], homeCity = jsonData['user']['homeCity'], bio = jsonData['user']['bio'], twitter = twttr ) # save dat ish user.save() # check to see if the venue exists try: venue = Venue.objects.get(venueId = jsonData['venue']['id']) # if not, then create it! except Exception: # see if the contact stuff exists try: phn = jsonData['venue']['contact']['phone'] except: phn = None try: twttr = jsonData['venue']['contact']['twitter'] except: twttr = None # make the venue model venue = Venue( venueId = jsonData['venue']['id'], name = jsonData['venue']['name'], phone = phn, twitter = twttr, address = jsonData['venue']['location']['address'], lat = jsonData['venue']['location']['lat'], lng = jsonData['venue']['location']['lng'], postalCode = jsonData['venue']['location']['postalCode'], city = jsonData['venue']['location']['postalCode'], state = jsonData['venue']['location']['state'], country = jsonData['venue']['location']['country'], categoryId = jsonData['venue']['categories'][0]['id'], categoryName = jsonData['venue']['categories'][0]['name'], categoryPluralName = jsonData['venue']['categories'][0]['pluralName'], categoryShortName = jsonData['venue']['categories'][0]['shortName'], categoryIcon = jsonData['venue']['categories'][0]['icon'], categoryPrimary = jsonData['venue']['categories'][0]['primary'], statsCheckinsCount = jsonData['venue']['stats']['checkinsCount'], statsUsersCount = jsonData['venue']['stats']['usersCount'], statsTipsCount = jsonData['venue']['stats']['tipCount'], statsLikesCount = jsonData['venue']['likes']['count'], url = jsonData['venue']['url'] ) # save dat ish venue.save() checkin = Checkin( checkinId = jsonData['id'], createdAt = datetime.datetime.fromtimestamp(jsonData['createdAt']), timezone = jsonData['timeZone'], user = user, venue = venue ) checkin.save() # grab the mayor mayorJson = simplejson.loads(urllib2.urlopen( "https://api.foursquare.com/v2/venues/" + jsonData['venue']['id'] + "?oauth_token=Y10QHO1ZKLBPAXKUZPKSHBFW5WVRKURG0S2CKBX2LA04ERZS&v=20120608").read() ) mayorId = mayorJson['response']['venue']['mayor']['user']['id'] # check to see if mayor is in DB, if not then add it try: mayor = FoursquareUser.objects.get(userId = mayorId) venue.mayor = mayor except: # we have to check since since the twitter field isn't always there try: twttr = mayorJson['response']['venue']['mayor']['user']['contact']['twitter'], except: twttr = None, user = FoursquareUser( userId = mayorJson['response']['venue']['mayor']['user']['id'], firstName = mayorJson['response']['venue']['mayor']['user']['firstName'], lastName = mayorJson['response']['venue']['mayor']['user']['lastName'], photo = mayorJson['response']['venue']['mayor']['user']['photo'], gender = mayorJson['response']['venue']['mayor']['user']['gender'], homeCity = mayorJson['response']['venue']['mayor']['user']['homeCity'], bio = mayorJson['response']['venue']['mayor']['user']['bio'], twitter = twttr ) # save dat ish user.save() venue.mayor = user return HttpResponse("OK\r\n") except Exception as steve: return HttpResponseServerError("ERROR" + " " + steve.message + "\r\n") finally: print r.status else: return HttpResponseServerError("Push some ish and get back to me\r\n")