def add(request, pid="0"): """Course add page view""" if not request.user.is_authenticated(): return HttpResponseRedirect('/users/auth_login') if request.method == 'POST': # if the form has been submitted... form = EditPeriodForm(request.POST) # A form bound to the POST data if form.is_valid() and form.check_conflict(pid): # Check validation new_period = Period( code=form.cleaned_data['code'], name=form.cleaned_data['name'], lecturer=form.cleaned_data['lecturer'], position=(int(form.cleaned_data['day'])-1)*10+int(form.cleaned_data['start']), length=form.cleaned_data['length'], timetable_id=pid) new_period.save() return HttpResponseRedirect('/') # Redirect after POST else: return HttpResponseRedirect('/users/gateway/do=6') else: form = EditPeriodForm() return render( request, 'periods/edit/index.html', { 'form': form } )
def my_home(): categorys_list=[] categorys=Category.get_categorys() for category in categorys: periods=Period.get_index_periods(cid=category.id) categorys_list.append((category.name,periods)) hot_products = Period.get_hot_products() return render_template('index.html', categorys_list=categorys_list, hot_products=hot_products)
def get(self): # Check if datasets are loaded in datastore # Items in datastore d = Dataset.query().count() # Items in CDB q = "select count(*) as c from resource_staging" + \ " where ipt is true and networks like '%VertNet%';" c = cartodb_query(q)[0]['c'] # Number of reports stored in the datastore num_reports = Report.query().count() periods = Period.query() num_periods = periods.count() periods_done = Period.query(Period.status == "done") num_periods_done = periods_done.count() periods_progress = Period.query(Period.status == "in progress") num_periods_progress = periods_progress.count() periods_failed = Period.query(Period.status == "failed") num_periods_failed = periods_failed.count() resp = { "Datastore integrity": [ {"Datasets in CartoDB": c}, {"Datasets in the Datastore": d} ], "Report periods": [ {"Stored periods": num_periods}, {"Stored reports": num_reports}, {"Periods completed": num_periods_done}, {"Periods in progress": num_periods_progress}, {"Periods failed": num_periods_failed}, ] } if c != d or c == 0: dataset_setup_url = "http://%s/setup_datasets" % _HOSTNAME resp["Datastore integrity"].append({"URL for dataset setup": dataset_setup_url}) if num_periods > 0: links_to_periods = ["http://%s/status/period/%s" % (_HOSTNAME, x.key.id()) for x in periods.fetch()] resp["Report periods"].append({"Links to periods": links_to_periods}) if num_periods_done > 0: resp['Report periods'].append({'List of periods done': [x.period.strftime("%Y-%m") for x in periods_done.fetch()]}) if num_periods_progress > 0: resp['Report periods'].append({'List of periods in progress': [x.period.strftime("%Y-%m") for x in periods_progress.fetch()]}) if num_periods_failed > 0: resp['Report periods'].append({'List of periods failed': [x.period.strftime("%Y-%m") for x in periods_failed.fetch()]}) self.response.headers['content-type'] = "application/json" self.response.write(json.dumps(resp))
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([]) for period in schedule_day.schedule: schedule.append([[period]]) return render(request, "scanner/schedule.html", {'schedule_table': schedule})
def create_tables(): auth.User.create_table(fail_silently=True) Users.create_table(fail_silently=True) Role.create_table(fail_silently=True) Category.create_table(fail_silently=True) Product.create_table(fail_silently=True) Period.create_table(fail_silently=True) Order_detail.create_table(fail_silently=True) Address.create_table(fail_silently=True) Show.create_table(fail_silently=True) UserRoles.create_table(fail_silently=True) Configure.create_table(fail_silently=True) WinRecord.create_table(fail_silently=True)
def fill_dummy_data(): p = Period(name="H1") p.save() i = Instrument(name="GBPUSD", description="The cable!", is_forex = True) i.save() price = 1.4567 initial_date = datetime.datetime(2014,05,01,hour=12,minute=00,second=00, tzinfo=utc) for x in range(1000): tstamp = initial_date + (x * timedelta(hours=1)) price += random.randint(1,3) * random.randint(-1,1) * random.randint(0, 10) / 1e4 ibar = IBar(start_time = tstamp, open=price, high=price, low=price, close=price, period=p, instrument=i) ibar.save()
def create_period(pro_id, tcount, number=None): if number: Period.create( product=pro_id, number=number, total_count=tcount, all_num=create_all_num(tcount), ) else: Period.create( product=pro_id, total_count=tcount, all_num=create_all_num(tcount), )
def pay_handler(): if request.method =='POST': data = request_form_to_dict() pid = int(data.get("pid")) count = int(data.get("amount")) period=Period.get(id=pid) time_now=datetime.now() left=period.total_count-period.join_count if left >= count: num = get_num(pid, count) # 创建或更新夺宝订单明细记录 create_or_update_order_detail(current_user.id, pid, { "count": count, "created_datetime": time_now, "num": num }) # 更新用户余额 update_user(current_user.id, current_user.balance - count) if left == count: kj_time = get_kj_time(time_now) update_period(pid, { "join_count": period.join_count + count, "status": 1, "end_time": time_now, "kj_count": create_kj_count(time_now), "kj_time": kj_time, }) create_period(period.product.id, period.total_count, period.number+ 1) else: update_period(pid,{ "join_count": period.join_count + count, }) return redirect(url_for('period_detail',pid=pid))
def enroll(request, pid='0'): """Course enroll page view""" if not request.user.is_authenticated(): return HttpResponseRedirect('/users/auth_login') if request.method == 'GET': tb_array = Timetable.objects.filter(owner=request.user.id) if tb_array.exists(): tid = tb_array[0].owner else: tid = 0 periods = Period.objects.get(id=pid) periods_array = Period.objects.filter(timetable_id=tid) pos = periods.position leg = periods.length free = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73] for f in free: f = True for p in periods_array: free[p.position] = False j = p.position while j <= p.position + p.length-1: if (j > 0) and (j < 71): free[j] = False j += 1 j = pos while j <= pos+leg-1: if j > 70: return HttpResponseRedirect('/users/gateway/do=5') if not free[j]: return HttpResponseRedirect('/users/gateway/do=5') else: free[j] = False j += 1 new_period = Period(code=periods.code, name=periods.name, period_type=periods.period_type, lecturer=periods.lecturer, position=periods.position, length=periods.length, timetable_id=tid) new_period.save() return HttpResponseRedirect('/')
def product_all(): page = int(request.args.get("page", 1)) order = request.args.get("order") cid = request.args.get("cid") if cid: current_cate=Category.get(id=cid) else: current_cate=None periods=Period.get_list_periods(cid=cid,page=page,order=order) return render_template( 'new_list.html', periods=periods,order=order,cid=cid,current_cate=current_cate)
def get_num(pid, price): period = Period.get(id=pid) all_seq = str(period.all_num).split(' ') random_seq = random.sample(all_seq, price) random_text = ' '.join(random_seq) left_seq = set(all_seq) - set(random_seq) left_text = ' '.join(left_seq) period.all_num = left_text period.save() return random_text
def update_period(pid, data): period = Period.get(id=int(pid)) if data.get("status"): period.join_count = data["join_count"] period.status = data["status"] period.end_time = data["end_time"] period.kj_count = data["kj_count"] period.kj_time = data["kj_time"] else: period.join_count = data["join_count"] period.save()
class PeriodTest(TestCase): def __init__(self, *args, **kwargs): super(PeriodTest, self).__init__(*args, **kwargs) self.h1period = Period(name="H1") self.m15period = Period(name="M15") def test_get_or_create(self): p = Period.get_period("M30") self.assertEqual(p.get_numeric(), 30) self.assertTrue(p.get_unit_letter() == "M") # TEST FAILING ! self.assertEqual(p.get_py_tdelta(), timedelta(minutes=30)) def test_get_numeric(self): self.assertTrue(self.h1period.get_numeric() == 1) self.assertTrue(self.m15period.get_numeric() == 15) def test_get_letter(self): self.assertTrue(self.h1period.get_unit_letter() == "H") self.assertTrue(self.m15period.get_unit_letter() == "M") def test_get_timedelta(self): h1tdelta = timedelta(hours=1) m15tdelta = timedelta(minutes=15) self.assertAlmostEquals(self.h1period.get_py_tdelta(), h1tdelta) self.assertAlmostEquals(self.m15period.get_py_tdelta(), m15tdelta)
def putMenu(self, date, periodId): """ date format: XXXX-XX-XX, peroid: 481,482,483 for breakfast, lunch and dinner, 1778 and 1779 for other two """ values = {} values['LocationId'] = "1965" # fixed for ARA values['PeriodId'] = periodId # 481,482,483 for breakfast, lunch and dinner, 1778 and 1779 for other two values['MenuDate'] = date values['UIBuildDateForm'] = date data = urllib.urlencode(values) url = "http://rose-hulman.campusdish.com/Commerce/Catalog/Menus.aspx" geturl = url + "?" + data print geturl request = urllib2.Request(geturl) response = urllib2.urlopen(request) soup = BeautifulSoup(response.read()) blocks = soup.find_all('div', class_='menu-details-station') if periodId == 481: pName = "Breakfast" elif periodId == 482: pName = "Lunch" elif periodId == 483: pName = "Dinner" elif periodId == 1778: pName = "Con't Breakfast" elif periodId == 1779: pName = "Soup & Salad" period = Period(selectDate=date, name=pName) period.put() for block in blocks: # print block.h2.string, "------" category = Category(parent=period.entityKey, name=block.h2.string) category.put() for item in block.find_all('div', class_='menu-name'): # print " ", item.a.string dish = Dish(parent=category.entityKey, name=item.a.string) dish.put()
def event_index(request): if request.method == 'GET': page_size = int(request.GET.get('pageSize',settings.DEFAUTL_PAGE_SIZE)) page_num = long(request.GET.get('pageNum',1)) order_str = title_field_html.get_order_str(request) query = Event.all().filter('owner =',users.get_current_user()) if order_str: query = query.order(order_str) else: query = query.order('-start') context = title_field_html.pagination_context(query.count(),page_num,page_size) context['object_list'] = query.fetch(page_size,offset=(page_num-1)*page_size) return render_to_response('work_note/event_list.html',context, context_instance=RequestContext(request)) elif request.method == 'POST': f = EventForm(request.POST) if f.is_valid(): event = f.save(commit=False) event.owner = users.get_current_user() period = Period(start=event.start,finish=event.finish) if event.finish: delta = event.finish - event.start event.total_work_time = delta.days*24*3600 + delta.seconds event.put() period.event = event period.put() event.set_last_period(period) event.put() logging.info('%s created event named %s.'%(users.get_current_user(),event.summary)) return HttpResponseRedirect(str(event.key())) else: return render_to_response('work_note/event_form.html', { 'form': f, "submit_times":int(request.POST['submit_times']) - 1, 'display_cancel':request.POST.get('display_cancel','true'), },context_instance=RequestContext(request)) raise Http404
def period_detail(): pid=request.args.get("pid") join_records = None count_now_time = None user_join_record = None zj_user_join_record = None newest_period = None period = Period.get_period(pid) newest_period = get_newest_period(period.product.id) join_records=get_join_records(period.kj_time) if period.status==1: join_records = get_join_records(period.end_time) count_now_time = time.time() newest_period = get_newest_period(period.product.id) if period.status == 2: zj_user_join_record = get_single_join_record(period.zj_user.id, pid) if current_user.get_id(): user_join_record = get_single_join_record(current_user.id, pid) return render_template('shop.html', period=period, join_records=join_records, count_now_time=count_now_time, newest_period=newest_period, user_join_record=user_join_record, zj_user_join_record=zj_user_join_record)
def initialize_extraction(self, period=None, force=None): """Check if Period parameter is valid, if the Period entity already exists and create a new Period.""" self.response.headers['Content-Type'] = "application/json" # Check that 'period' is provided if not self.period: logging.error("Period not found on POST body. Aborting.") self.error(400) resp = { "status": "error", "message": "Period not found on POST body. " + "Aborting." } self.response.write(json.dumps(resp) + "\n") return 1 # Check that 'period' is valid if len(self.period) != 6: self.error(400) resp = { "status": "error", "message": "Malformed period. Should be YYYYMM (e.g., 201603)" } self.response.write(json.dumps(resp) + "\n") return 1 # Get existing period period_key = ndb.Key("Period", self.period) period_entity = period_key.get() # If existing, abort or clear and start from scratch if period_entity: if self.force is not True: logging.error("Period %s already exists. " % self.period + "Aborting. To override, use 'force=true'.") resp = { "status": "error", "message": "Period %s already exists. " % self.period + "Aborting. To override, use 'force=true'." } self.response.write(json.dumps(resp) + "\n") return 1 else: logging.warning("Period %s already exists. " % self.period + "Overriding.") # Delete Reports referencing period r = Report.query().filter(Report.reported_period == period_key) to_delete = r.fetch(keys_only=True) logging.info("Deleting %d Report entities" % len(to_delete)) deleted = ndb.delete_multi(to_delete) logging.info("%d Report entities removed" % len(deleted)) # Delete Period itself logging.info("Deleting Period %s" % period_key) period_key.delete() logging.info("Period entity deleted") # Create new Period (id=YYYYMM) logging.info("Creating new Period %s" % self.period) y, m = (int(self.period[:4]), int(self.period[-2:])) p = Period(id=self.period) p.year = y p.month = m p.status = 'in progress' period_key = p.put() # Check if period_key: logging.info("New Period %s created successfully." % self.period) logging.info("New period's key = %s" % period_key) else: self.error(500) logging.error("Could not create new Period %s" % self.period) resp = { "status": "error", "message": "Could not create new Period %s" % self.period } self.response.write(json.dumps(resp) + "\n") return 1 # Clear temporary entities keys_to_delete = ReportToProcess.query().fetch(keys_only=True) logging.info("Deleting %d temporal (internal use only) entities" % len(keys_to_delete)) ndb.delete_multi(keys_to_delete) return 0
def get(self): # Check if datasets are loaded in datastore # Items in datastore d = Dataset.query().count() # Items in Carto q = "select count(*) as c from resource_staging" + \ " where ipt is true and networks like '%VertNet%';" c = carto_query(q)[0]['c'] # Number of reports stored in the datastore num_reports = Report.query().count() periods = Period.query() num_periods = periods.count() periods_done = Period.query(Period.status == "done") num_periods_done = periods_done.count() periods_progress = Period.query(Period.status == "in progress") num_periods_progress = periods_progress.count() periods_failed = Period.query(Period.status == "failed") num_periods_failed = periods_failed.count() resp = { "Datastore integrity": [ {"Datasets in Carto": c}, {"Datasets in the Datastore": d} ], "Report periods": [ {"Stored periods": num_periods}, {"Stored reports": num_reports}, {"Periods completed": num_periods_done}, {"Periods in progress": num_periods_progress}, {"Periods failed": num_periods_failed}, ] } if c != d or c == 0: dataset_setup_url = "http://%s/admin/setup/datasets" % _HOSTNAME resp["Datastore integrity"].append({"URL for dataset setup": dataset_setup_url}) if num_periods > 0: links_to_periods = ["http://%s/admin/status/period/%s" % (_HOSTNAME, x.key.id()) for x in periods.fetch()] resp["Report periods"].append({"Links to periods": links_to_periods}) if num_periods_done > 0: resp['Report periods'].append({'List of periods done': [x.period.strftime("%Y-%m") for x in periods_done.fetch()]}) if num_periods_progress > 0: resp['Report periods'].append({'List of periods in progress': [x.period.strftime("%Y-%m") for x in periods_progress.fetch()]}) if num_periods_failed > 0: resp['Report periods'].append({'List of periods failed': [x.period.strftime("%Y-%m") for x in periods_failed.fetch()]}) headers = { 'User-Agent': 'VertNet', 'Accept': 'application/vnd.github.v3+json', 'Authorization': 'token {0}'.format(apikey('ghb')) } # API URL https://api.github.com/rate-limit rpc = urlfetch.create_rpc() url = '/'.join([GH_URL, 'users', 'VertNet']) urlfetch.set_default_fetch_deadline(60) urlfetch.make_fetch_call(rpc, url, headers=headers) h = rpc.get_result().headers u = rpc.get_result().content resp['url'] = url user = {} user['content']=json.loads(u) timefloat = float(h['x-ratelimit-reset']) expires = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timefloat)) user['x-ratelimit-limit'] = h['x-ratelimit-limit'] user['x-ratelimit-remaining'] = h['x-ratelimit-remaining'] user['x-ratelimit-reset'] = expires resp['user'] = user self.response.headers['content-type'] = "application/json" self.response.write(json.dumps(resp))
def _create_or_add_period(self, period_name, parentnode, extras): period = Period(parentnode=parentnode, short_name=period_name, long_name=period_name.capitalize(), start_time=datetime.now(), end_time=datetime.now() + timedelta(days=5 * 30)) try: period.full_clean() period.save() except ValidationError: period = Period.objects.get(parentnode=parentnode, short_name=period_name) # add the extras (only admins allowed in subject) for admin in extras['admin']: period.admins.add(self._create_or_add_user(admin)) if extras['begins']: period.start_time = datetime.now() + timedelta(days=int(extras['begins'][0]) * 30) if extras['ends']: period.end_time = period.start_time + timedelta(days=int(extras['ends'][0]) * 30) elif extras['begins'] and not extras['ends']: period.end_time = period.start_time + timedelta(5 * 30) if extras['ln']: period.long_name = extras['ln'][0] period.full_clean() period.save() vars(self)[parentnode.short_name + '_' + period.short_name] = period return period
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() for period in schedule_day 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 create_from_path(path): """ Create a Node, Subject, Period, Assignment or AssignmentGroup from ``path``. Examples:: assignmentgroup = create_from_path( 'ifi:inf1100.spring05.oblig1.student1,student2') oblig1 = create_from_path( 'ifi:inf1100.spring05.oblig1') """ split = path.split(':', 1) nodes = split[0].split('.') for nodename in nodes: node = Node(short_name=nodename, long_name=nodename.capitalize()) try: node.clean() node.save() except: node = Node.objects.get(short_name=nodename) last = node if len(split) != 2: return last pathsplit = split[1].split('.') # Subject subjectname = pathsplit[0] subject = Subject(parentnode=node, short_name=subjectname, long_name=subjectname.capitalize()) try: subject.clean() subject.save() except: subject = Subject.objects.get(short_name=subjectname) last = subject # Period if len(pathsplit) > 1: periodname = pathsplit[1] period = Period(parentnode=subject, short_name=periodname, long_name=periodname.capitalize(), start_time=datetime.now(), end_time=datetime.now() + timedelta(10)) try: period.clean() period.save() except: period = Period.objects.get(parentnode=subject, short_name=periodname) last = period # Assignment if len(pathsplit) > 2: assignmentname = pathsplit[2] assignment = Assignment(parentnode=period, short_name=assignmentname, long_name=assignmentname.capitalize(), publishing_time=datetime.now()) assignment.clean() try: assignment.save() except: assignment = Assignment.objects.get(parentnode=period, short_name=assignmentname) last = assignment # Candidates if len(pathsplit) > 3: usernames = pathsplit[3].split(',') users = [] for u in usernames: user = User(username=u) try: user.save() except: user = User.objects.get(username=u) users.append(user) assignment_group = AssignmentGroup(parentnode=assignment) assignment_group.clean() assignment_group.save() for user in users: assignment_group.candidates.add(Candidate(student=user)) last = assignment_group return last
def test_bars(self): instrument = Instrument.objects.get(name="GBPUSD") list = instrument.get_bar_collection(Period.get_period("H1")) self.assertTrue(list) # only confirm a list is returned, tested manually = order working
def _create_or_add_period(self, period_name, parentnode, extras): period = Period(parentnode=parentnode, short_name=period_name, long_name=period_name.capitalize(), start_time=datetime.now(), end_time=datetime.now() + timedelta(days=5 * 30)) try: period.full_clean() period.save() except ValidationError: period = Period.objects.get(parentnode=parentnode, short_name=period_name) # add the extras (only admins allowed in subject) for admin in extras['admin']: period.admins.add(self._create_or_add_user(admin)) if extras['begins']: period.start_time = datetime.now() + timedelta( days=int(extras['begins'][0]) * 30) if extras['ends']: period.end_time = period.start_time + timedelta( days=int(extras['ends'][0]) * 30) elif extras['begins'] and not extras['ends']: period.end_time = period.start_time + timedelta(5 * 30) if extras['ln']: period.long_name = extras['ln'][0] period.full_clean() period.save() vars(self)[parentnode.short_name + '_' + period.short_name] = period return period
def create_from_path(path): """ Create a Node, Subject, Period, Assignment or AssignmentGroup from ``path``. Examples:: assignmentgroup = create_from_path( 'ifi:inf1100.spring05.oblig1.student1,student2') oblig1 = create_from_path( 'ifi:inf1100.spring05.oblig1') """ split = path.split(':', 1) nodes = split[0].split('.') for nodename in nodes: node = Node(short_name=nodename, long_name=nodename.capitalize()) try: node.clean() node.save() except: node = Node.objects.get(short_name=nodename) last = node if len(split) != 2: return last pathsplit = split[1].split('.') # Subject subjectname = pathsplit[0] subject = Subject(parentnode=node, short_name=subjectname, long_name=subjectname.capitalize()) try: subject.clean() subject.save() except: subject = Subject.objects.get(short_name=subjectname) last = subject # Period if len(pathsplit) > 1: periodname = pathsplit[1] period = Period(parentnode=subject, short_name=periodname, long_name=periodname.capitalize(), start_time=datetime.now(), end_time=datetime.now() + timedelta(10)) try: period.clean() period.save() except: period = Period.objects.get(parentnode=subject, short_name=periodname) last = period # Assignment if len(pathsplit) > 2: assignmentname = pathsplit[2] assignment = Assignment(parentnode=period, short_name=assignmentname, long_name=assignmentname.capitalize(), publishing_time=datetime.now()) assignment.clean() try: assignment.save() except: assignment = Assignment.objects.get(parentnode=period, short_name=assignmentname) last = assignment # Candidates if len(pathsplit) > 3: usernames = pathsplit[3].split(',') users = [] for u in usernames: try: user = get_user_model().objects.get(shortname=u) except get_user_model().DoesNotExist: user = get_user_model().objects.create_user(username=u) users.append(user) assignment_group = AssignmentGroup(parentnode=assignment) assignment_group.clean() assignment_group.save() for user in users: assignment_group.candidates.add(Candidate(student=user)) last = assignment_group return last
def test_get_or_create(self): p = Period.get_period("M30") self.assertEqual(p.get_numeric(), 30) self.assertTrue(p.get_unit_letter() == "M") # TEST FAILING ! self.assertEqual(p.get_py_tdelta(), timedelta(minutes=30))
def __init__(self, *args, **kwargs): super(PeriodTest, self).__init__(*args, **kwargs) self.h1period = Period(name="H1") self.m15period = Period(name="M15")
def announced(): count_now_time = time.time() periods = Period.get_announced_list() winrecords=WinRecord.get_winrecords() return render_template('announced.html', periods=periods, count_now_time=count_now_time,winrecords=winrecords)
def get_newest_period(proid): period = Period.select().where(Period.product == proid, Period.status == 0).get() return period
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 for 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':
def initialize_extraction(self, period=None, force=None): """Check if Period parameter is valid, if the Period entity already exists and create a new Period. """ self.response.headers['Content-Type'] = "application/json" # Check that 'period' is provided if not self.period: s = "Version: %s\n" % __version__ s += "Period not found on POST body. Aborting." logging.error(s) self.error(400) resp = {"status": "error", "message": s} self.response.write(json.dumps(resp) + "\n") return 1 # Check that 'period' is valid if len(self.period) != 6: s = "Version: %s\n" % __version__ s += "Malformed period. Should be YYYYMM (e.g., 201603)" logging.error(s) self.error(400) resp = {"status": "error", "message": s} self.response.write(json.dumps(resp) + "\n") return 1 # Get existing period period_key = ndb.Key("Period", self.period) period_entity = period_key.get() # If existing, abort or clear and start from scratch if period_entity: if self.force is not True: s = "Version: %s\n" % __version__ s += "Period %s already exists. " % self.period s += "Aborting. To override, use 'force=true'." logging.error(s) resp = {"status": "error", "message": s} self.response.write(json.dumps(resp) + "\n") return 1 else: s = "Version: %s\n" % __version__ s += "Period %s already exists. " % self.period s += "Overriding." logging.warning(s) # Delete Reports referencing period r = Report.query().filter(Report.reported_period == period_key) to_delete = r.fetch(keys_only=True) s = "Version: %s\n" % __version__ s += "Deleting %d Report entities" % len(to_delete) logging.info(s) deleted = ndb.delete_multi(to_delete) s = "Version: %s\n" % __version__ s += "%d Report entities removed" % len(deleted) logging.info(s) # Delete Period itself s = "Version: %s\n" % __version__ s += "Deleting Period %s" % period_key logging.info(s) period_key.delete() s = "Version: %s\n" % __version__ s += "Period %s deleted" % period_key logging.info(s) # Create new Period (id=YYYYMM) s = "Version: %s\n" % __version__ s += "Creating new Period %s" % self.period logging.info(s) y, m = (int(self.period[:4]), int(self.period[-2:])) p = Period(id=self.period) p.year = y p.month = m p.status = 'in progress' period_key = p.put() # Check if period_key: s = "Version: %s\n" % __version__ s += "New Period %s created successfully" % self.period s += "with key %s" % period_key logging.info(s) else: self.error(500) s = "Version: %s\n" % __version__ s += "Could not create new Period %s" % self.period logging.error(s) resp = {"status": "error", "message": s} self.response.write(json.dumps(resp) + "\n") return 1 # Clear temporary entities keys_to_delete = ReportToProcess.query().fetch(keys_only=True) s = "Version: %s\n" % __version__ s += "Deleting %d temporal (internal use only) entities" % len( keys_to_delete) logging.info(s) ndb.delete_multi(keys_to_delete) return 0