def test_model(): request_time = now() obj = Response( url="https://google.com", error=None, status_code=200, load_time=0.23, request_time=request_time, body=None, ) assert obj.ok assert obj.to_dict()["url"] == "https://google.com" assert obj.to_dict()["load_time"] == 0.23 assert isinstance(obj.json_dumps(), str) error_status = Response( url="https://google.com", error="error_500", status_code=500, load_time=0.23, request_time=now(), body=None, ) assert not error_status.ok
def create_default_settings(apps, schema_editor): """ Creates some default settings that other apps rely on. If a setting already exists, leaves them be. Defaults are based on Fall 2015 values. """ Setting = apps.get_model("core", "Setting") now_obj = now() # make sure we don't collide with current order nums current_order_nums = set([x.order_num for x in Setting.objects.all()]) for order_num, name in enumerate(defaults): while order_num in current_order_nums: order_num += 1 current_order_nums.add(order_num) if not Setting.objects.filter(name=name): Setting.objects.create(name=name, time_set=now_obj, order_num=order_num, **defaults[name])
def get(self, request, *args, **kwargs): now_obj = now() year = kwargs.get('year') month = kwargs.get('month') year, month = parse_year_month(year, month) months_list = [(num, name) for num, name in enumerate(list(calendar.month_name)) if num != 0] date = datetime.date(year, month, 1) next_month = date + relativedelta(months=1) prev_month = date + relativedelta(months=-1) weeks = weeks_with_shifts(month=month, year=year) context = { 'months_list': months_list, 'weeks': weeks, 'now': now_obj, 'month': month, 'year': year, 'next_year': (year + 1), 'prev_year': (year - 1), 'next_month': next_month, 'prev_month': prev_month, } return render(request, 'shifts/month.html', context)
def get_initial(self): now = utils.now() closes_default = (now + datetime.timedelta(days=7)).replace(hour=17, minute=0, second=0, microsecond=0) month = self.kwargs.get("month") year = self.kwargs.get("year") year, month = utils.parse_year_month(year, month, default=None) return {"opens": now, "closes": closes_default, "month": month, "year": year}
def get(self, request, *args, **kwargs): month = kwargs.get("month") year = kwargs.get("year") year, month = utils.parse_year_month(year, month, default=None) now = utils.now() if not month or not year: # show choose form choose_month_form = ChooseMonthForm() return render(request, "tours/initialize_choose_month.html", {"form": choose_month_form}) try: month = int(month) year = int(year) except: raise Http404 # make sure this month isn't initialized or out of allowed range date_obj = datetime.datetime(year, month, 1) current = datetime.datetime(now.year, now.month, 1) last_allowed = utils.add_months(current, 12, True) # make sure this month isn't initialized or out of allowed range if tours_utils.is_initialized(month=month, year=year) or date_obj < current or date_obj > last_allowed: raise PermissionDenied weeks = calendar.Calendar().monthdays2calendar(year, month) return render(request, "tours/initialize_month.html", {"weeks": weeks, "month": month, "year": year})
def tours_status(self, semester=None, year=None): """ Returns dictionary of form: { 'status': 'complete'|'incomplete'|'projected', 'num_required': int, 'num_remaining': int, 'num_to_sign_up': int, 'num_extra': int, 'date_projected': date|None, 'complete': [], 'late': [], 'missed': [], 'upcoming': [], 'tours': [], } """ year, semester = core_utils.parse_year_semester(year, semester) now_obj = core_utils.now() semester_tours = self.tours.filter(counts_for_requirements=True).semester(semester=semester, year=year).order_by('time') complete = semester_tours.filter(missed=False, time__lte=now_obj) late = semester_tours.filter(late=True, missed=False, time__lte=now_obj) missed = semester_tours.filter(missed=True, time__lte=now_obj) past = semester_tours.filter(time__lt=now_obj) upcoming = semester_tours.filter(time__gte=now_obj) num_required = self.tours_required_num(semester=semester, year=year) num_remaining = num_required - complete.count() num_extra = abs(min(num_remaining, 0)) num_remaining = max(num_remaining, 0) num_to_sign_up = max(num_remaining - upcoming.count(), 0) # calculate status if num_remaining <= 0: status = 'complete' elif num_remaining <= upcoming.count(): status = 'projected' else: status = 'incomplete' if status == 'projected': completion_obj = upcoming[num_remaining - 1] date_projected = completion_obj.time else: date_projected = None return { 'status': status, 'num_required': num_required, 'num_remaining': num_remaining, 'num_to_sign_up': num_to_sign_up, 'num_extra': num_extra, 'date_projected': date_projected, 'complete': complete, 'late': late, 'missed': missed, 'past': past, 'upcoming': upcoming, 'tours': semester_tours, }
def month_is_open(month, year, return_tuple=False): """ Checks if a month is 'open' for tour claiming. Returns True/False. Optionally returns a tuple that also includes the closing date. """ now = core_utils.now() try: latest = OpenMonth.objects.filter(month=month, year=year).latest('pk') except OpenMonth.DoesNotExist: latest = None if latest: if latest.opens <= now <= latest.closes: if return_tuple: return True, latest.closes else: return True else: if return_tuple: return False, None else: return False else: if return_tuple: return False, None else: return False
def get(self, request, *args, **kwargs): month = kwargs.get('month') year = kwargs.get('year') year, month = utils.parse_year_month(year, month, default=None) now = utils.now() if not month or not year: # show choose form choose_month_form = ChooseMonthForm() return render(request, 'tours/initialize_choose_month.html', {'form': choose_month_form}) try: month = int(month) year = int(year) except: raise Http404 # make sure this month isn't initialized or out of allowed range date_obj = datetime.datetime(year, month, 1) current = datetime.datetime(now.year, now.month, 1) last_allowed = utils.add_months(current, 12, True) # make sure this month isn't initialized or out of allowed range if tours_utils.is_initialized( month=month, year=year) or date_obj < current or date_obj > last_allowed: raise PermissionDenied weeks = calendar.Calendar().monthdays2calendar(year, month) return render(request, 'tours/initialize_month.html', { 'weeks': weeks, 'month': month, 'year': year })
def message_append(self, key, message): self.task._executed = True self.message.append({ 'type': key, 'message': message, 'time': utils.now(fmt='%Y-%m-%d %H:%M:%S'), })
async def check( # pylint: disable=arguments-differ self, session: ClientSession, *, url: str = None, **kwargs: Any) -> Response: """ Fetching page HTML """ if not url: raise TypeError("url doen not set") start = now() try: response = await session.get(url, headers=self.headers) except asyncio.TimeoutError: logger.warning("cannot reach {}, host does not respond (timeout)", url) return Response( url, error="host does not respond (timeout)", status_code=-1, load_time=0, request_time=now(), body=None, ) except aiohttp.ClientError as err: logger.warning("cannot reach {}, {}", url, err) return Response( url, error=f"{err}", status_code=-1, load_time=0, request_time=now(), body=None, ) load_time = (now() - start).total_seconds() logger.debug("{} returns {} -- {}", url, response.status, load_time) body = await response.text() return Response( url, error=None if response.ok else f"returns {response.status} response", status_code=response.status, load_time=load_time, request_time=now(), body=body, )
def get(self, request, *args, **kwargs): if kwargs.get("public"): # make sure this user is active if not request.user.person.is_active: raise PermissionDenied else: # make sure this is a board member try: request.user.groups.get(name="Board Members") except Group.DoesNotExist: raise PermissionDenied now = utils.now() year = kwargs.get("year") month = kwargs.get("month") year, month = utils.parse_year_month(year, month) months_list = [(num, name) for num, name in enumerate(list(calendar.month_name)) if num != 0] date = datetime.date(year, month, 1) next_month = date + relativedelta(months=1) prev_month = date + relativedelta(months=-1) primary_tour_coordinator = get_person_by_position("Tour Coordinator (Primary)", "Tour Coordinator") is_open, date_closes = tours_utils.month_is_open(month=month, year=year, return_tuple=True) if is_open: public_url = request.build_absolute_uri( unicode(reverse("public:month", kwargs={"year": year, "month": month})) ) else: public_url = None open_eligible = tours_utils.open_eligible(month=month, year=year) weeks_with_tours = tours_utils.weeks_with_tours(month=month, year=year) context = { "months_list": months_list, "weeks": weeks_with_tours, "now": now, "month": month, "year": year, "next_year": (year + 1), "prev_year": (year - 1), "next_month": next_month, "prev_month": prev_month, "month_initialized": tours_utils.is_initialized(month=month, year=year), "is_open": is_open, "date_closes": date_closes, "open_eligible": open_eligible, "public_url": public_url, "primary_tour_coordinator": primary_tour_coordinator, } if kwargs.get("public"): return render(request, "public/month.html", context) elif kwargs.get("print") is True: return render(request, "tours/month_print.html", context) else: return render(request, "tours/month.html", context)
def time_line_data(self, request): start_date = request.query_params.get('start_date', None) # 2020-12-01 과 같은 포맷으로 입력 start_date = '2020-11-11' if not start_date: return Response('start_date 파라미터는 필수 입력값입니다.', status=status.HTTP_400_BAD_REQUEST) converted_start_date = self.convert_start_time(start_date) if not start_date: return Response( f'start_date 값 {start_date} 은 datetime 으로 변환할 수 없습니다.', status=status.HTTP_400_BAD_REQUEST) converted_end_date = self.convert_end_time(now()) character_ids = self.user_info(request) items_object = [] item_image_object = [] item_image_url = 'https://img-api.neople.co.kr/df/items/' item_rarity_object = [] for character_id in character_ids: url = f'https://api.neople.co.kr/df/servers/{server_name}/characters/{character_id}/timeline?startDate={converted_start_date}&endDate={converted_end_date}&code=513&apikey={settings.DF_API_KEY}' request = urllib.request.Request(url) response = urllib.request.urlopen(request) read_data = response.read() encoding = response.info().get_content_charset('utf8') timeline_list = json.loads(read_data.decode(encoding)) timeline_rows = timeline_list['timeline'] timeline_datas = timeline_rows['rows'] for timeline_data in timeline_datas: dungeon_item_datas = timeline_data items = dungeon_item_datas['data'] if items['itemRarity'] == '에픽': items_object.append(items) item_image_object.append(item_image_url + items['itemId']) item_names = items['itemName'] item_rarity_object.append(item_names) else: print('에픽 아님 아무튼 아님') result = { 'item_rarity_object': item_rarity_object, 'item_image_object': item_image_object } return result
def get_initialize_month_choices(): now = core_utils.now() months = [core_utils.add_months(now, i) for i in range(0, 13)] months_choices = [] for month in months: if not is_initialized(month=month.month, year=month.year): months_choices.append((u'{}/{}'.format(month.year, month.month), month.strftime('%B %Y'))) return months_choices
async def on_valid_message(self, message): self.sources_statistics[message.source_name] = SourceStatistics( message.source_name, message.source_status, message.message_number, now(), ) for observer in self.watchers: await observer.notify(message)
def claim_eligible(self): from tours.utils import month_is_open now = core_utils.now() # check if the month is open if not month_is_open(month=self.time.month, year=self.time.year): return False # month is open, check if the tour is in the future return self.time >= now
def save(self, *args, **kwargs): # avoid ciruclar import from core.utils import now now_obj = now() self.time_set = now_obj if not self.pk: # object is new, just save it return super(Setting, self).save(*args, **kwargs) else: # don't save it, create a new object instead Setting.objects.create(name=self.name, value=self.value, description=self.description, order_num=self.order_num, value_type=self.value_type, time_set=now_obj)
def inactive(self, semester=None, year=None): """ Includes only members who are inactive for the given semester and year """ if semester is None: semester = core_utils.current_semester() if year is None: year = core_utils.now().year else: year = int(year) semester = semester.lower() return self.filter(inactive_semesters__year__exact=year, inactive_semesters__semester=semester)
def get_initial(self): now = utils.now() closes_default = (now + datetime.timedelta(days=7)).replace( hour=17, minute=0, second=0, microsecond=0) month = self.kwargs.get('month') year = self.kwargs.get('year') year, month = utils.parse_year_month(year, month, default=None) return { 'opens': now, 'closes': closes_default, 'month': month, 'year': year }
def member_latest_semester(person): """ Finds the latest semester a member was in Crimson Key. For graduated members, this means the spring of their senior year. Otherwise, it's usually latest semester (as in current_semester()). Raises a ValueError if something goes wrong (e.g., a person in the db is not yet a member, i.e. member_since > current year). """ member_since = person.member_since_year grad_year = person.year semester = current_semester() year = now().year latest_semester = None latest_year = None if semester == 'fall': # if has graduated, return spring of their grad year if year >= grad_year: latest_semester = 'spring' latest_year = grad_year # if hasn't graduated else: if member_since > year: latest_semester = semester latest_year = member_since else: latest_semester = semester latest_year = year elif semester == 'spring': # if has graduated, return spring of their grad year if year > grad_year: latest_semester = 'spring' latest_year = grad_year # if hasn't graduated else: if member_since >= year: latest_semester = semester latest_year = member_since else: latest_semester = semester latest_year = year return latest_year, latest_semester
def send_reminder_texts(): """ Sends reminder texts for today's tours and shifts. """ now_obj = now() tours = Tour.objects.filter(time__day=now_obj.day, time__month=now_obj.month, time__year=now_obj.year, time__gte=now_obj).exclude(guide=None) for tour in tours: # send_tour_reminder_text.delay(tour) send_tour_reminder_text(tour) shifts = Shift.objects.filter(time__day=now_obj.day, time__month=now_obj.month, time__year=now_obj.year, time__gte=now_obj).exclude(person=None) for shift in shifts: # send_shift_reminder_text.delay(shift) send_shift_reminder_text(shift)
def get_context_data(self, **kwargs): context = super(EditPersonView, self).get_context_data(**kwargs) semester = current_semester() year = now().year initial_data = {'semester': semester, 'year': year, 'person': self.object} try: override_req = OverrideRequirement.objects.get(semester=semester, year=year, person=self.object) initial_data['tours_required'] = override_req.tours_required initial_data['shifts_required'] = override_req.shifts_required except OverrideRequirement.DoesNotExist: pass context['special_requirements_form'] = SpecialRequirementsForm(initial_data) context['semester'] = semester context['year'] = year context['site_admins_count'] = Person.objects.filter(site_admin=True).count() return context
def open_eligible(month, year): """ Checks whether a month is eligible to be opened. That is, it has not passed yet and is in the current semester. """ now = core_utils.now() month = int(month) year = int(year) # whether the month is in the current semester in_current_semester = (core_utils.current_semester(now) == core_utils.current_semester(datetime.datetime(year, month, 1))) and year == now.year # month is in the current semester, and is the current month or in the future, and the month is initialized if in_current_semester and month >= now.month and is_initialized(month=month, year=year): return True else: return False
def send_reminder_emails(): """ Sends reminder emails for tomorrow's tours and shifts. """ tomorrow = now() + datetime.timedelta(days=1) # get all of tomorrow's claimed tours tours = Tour.objects.filter(time__day=tomorrow.day, time__month=tomorrow.month, time__year=tomorrow.year).exclude(guide=None) for tour in tours: # send_tour_reminder_email.delay(tour) send_tour_reminder_email(tour) # get all of tomorrow's shifts shifts = Shift.objects.filter(time__day=tomorrow.day, time__month=tomorrow.month, time__year=tomorrow.year).exclude(person=None) for shift in shifts: # send_shift_reminder_email.delay(shift) send_shift_reminder_email(shift)
def get(self, request, *args, **kwargs): year = kwargs.get('year') semester = kwargs.get('semester') year, semester = parse_year_semester(year=year, semester=semester) prev_semester = delta_semester(semester=semester, year=year, delta=-1, as_dict=True) next_semester = delta_semester(semester=semester, year=year, delta=1, as_dict=True) collect_dues = dues_required(semester=semester, year=year) people = self.get_people(semester=semester, year=year) is_current_semester = semester == current_semester() and year == now().year # cache requirements status results so that we don't have to keep hitting the db for person in people: dues_status = person.dues_status(semester=semester, year=year) person.cached_status = { 'tours_status': person.tours_status(semester=semester, year=year), 'shifts_status': person.shifts_status(semester=semester, year=year), 'dues_status': dues_status, 'active': person.is_active(semester=semester, year=year) } # dues payments if collect_dues: paid = dues_status == 'complete' person.dues_payment_form = DuesPaymentForm(initial={'pk': person.pk, 'paid': paid}, prefix='pk_{}'.format(person.pk)) context = { 'semester': semester, 'year': year, 'people': people, 'prev_semester': prev_semester, 'next_semester': next_semester, 'collect_dues': collect_dues, 'is_current_semester': is_current_semester, } return render(request, 'profiles/roster.html', context)
def current_members(self, semester=None, year=None): if semester is None: semester = core_utils.current_semester() if year is None: year = core_utils.now().year else: year = int(year) semester = semester.lower() senior_year, freshman_year = core_utils.class_years(semester=semester, year=year, bookends_only=True) kwargs = {} if semester == 'fall': kwargs['member_since_year__lte'] = year else: kwargs['member_since_year__lt'] = year kwargs['year__lte'] = freshman_year kwargs['year__gte'] = senior_year return self.filter(**kwargs)
def send_reminder_emails(): """ Sends reminder emails for tomorrow's tours and shifts. """ tomorrow = now() + datetime.timedelta(days=1) # get all of tomorrow's claimed tours tours = Tour.objects.filter(time__day=tomorrow.day, time__month=tomorrow.month, time__year=tomorrow.year).exclude(guide=None) for tour in tours: # send_tour_reminder_email.delay(tour) send_tour_reminder_email(tour) # get all of tomorrow's shifts shifts = Shift.objects.filter( time__day=tomorrow.day, time__month=tomorrow.month, time__year=tomorrow.year).exclude(person=None) for shift in shifts: # send_shift_reminder_email.delay(shift) send_shift_reminder_email(shift)
def get(self, request, *args, **kwargs): if kwargs.get('public'): # make sure this user is active if not request.user.person.is_active: raise PermissionDenied else: # make sure this is a board member try: request.user.groups.get(name='Board Members') except Group.DoesNotExist: raise PermissionDenied now = utils.now() year = kwargs.get('year') month = kwargs.get('month') year, month = utils.parse_year_month(year, month) months_list = [(num, name) for num, name in enumerate(list(calendar.month_name)) if num != 0] date = datetime.date(year, month, 1) next_month = date + relativedelta(months=1) prev_month = date + relativedelta(months=-1) primary_tour_coordinator = get_person_by_position( 'Tour Coordinator (Primary)', 'Tour Coordinator') is_open, date_closes = tours_utils.month_is_open(month=month, year=year, return_tuple=True) if is_open: public_url = request.build_absolute_uri( unicode( reverse('public:month', kwargs={ 'year': year, 'month': month }))) else: public_url = None open_eligible = tours_utils.open_eligible(month=month, year=year) weeks_with_tours = tours_utils.weeks_with_tours(month=month, year=year) context = { 'months_list': months_list, 'weeks': weeks_with_tours, 'now': now, 'month': month, 'year': year, 'next_year': (year + 1), 'prev_year': (year - 1), 'next_month': next_month, 'prev_month': prev_month, 'month_initialized': tours_utils.is_initialized(month=month, year=year), 'is_open': is_open, 'date_closes': date_closes, 'open_eligible': open_eligible, 'public_url': public_url, 'primary_tour_coordinator': primary_tour_coordinator, } if kwargs.get('public'): return render(request, 'public/month.html', context) elif kwargs.get('print') is True: return render(request, 'tours/month_print.html', context) else: return render(request, 'tours/month.html', context)
def post(self, request, *args, **kwargs): month = kwargs.get('month') year = kwargs.get('year') year, month = utils.parse_year_month(year, month) now = utils.now() try: month = int(month) year = int(year) except: raise Http404 # make sure this month isn't initialized or out of allowed range date_obj = datetime.datetime(year, month, 1) current = datetime.datetime(now.year, now.month, 1) last_allowed = utils.add_months(current, 12, True) # make sure this month isn't initialized or out of allowed range if tours_utils.is_initialized( month=month, year=year) or date_obj < current or date_obj > last_allowed: raise PermissionDenied # process form selected_days = request.POST.get('selected_days', None) if selected_days is None: return HttpResponseBadRequest # make a counter of all selected days (i.e., days on which to have tours) if selected_days != '': selected_days_counter = Counter( [int(i) for i in selected_days.split(',')]) else: selected_days_counter = Counter() # make a counter of all days in the month month_dates_counter = Counter([ i for i in calendar.Calendar().itermonthdays(year, month) if i != 0 ]) canceled_days_counter = month_dates_counter - selected_days_counter for num, times in canceled_days_counter.items(): date = datetime.date(year, month, num) canceled_day = CanceledDay(date=date) canceled_day.save() # add default tours on non-blacked out days default_tours = DefaultTour.objects.all() weeks = calendar.Calendar().monthdatescalendar(year, month) for week in weeks: for date in week: if date.month == month and not CanceledDay.objects.filter( date=date): for default_tour in default_tours.filter( day_num=date.weekday): add_tour = Tour.objects.create( source=default_tour.source, time=datetime.datetime(date.year, date.month, date.day, default_tour.hour, default_tour.minute), notes=default_tour.notes, length=default_tour.length, default_tour=True) # mark month as initialized initialized_month = InitializedMonth.objects.create(month=month, year=year) return redirect('tours:month', month=month, year=year)
def is_upcoming(self): now = core_utils.now() if self.time > now: return True else: return False
def post(self, request, *args, **kwargs): month = kwargs.get("month") year = kwargs.get("year") year, month = utils.parse_year_month(year, month) now = utils.now() try: month = int(month) year = int(year) except: raise Http404 # make sure this month isn't initialized or out of allowed range date_obj = datetime.datetime(year, month, 1) current = datetime.datetime(now.year, now.month, 1) last_allowed = utils.add_months(current, 12, True) # make sure this month isn't initialized or out of allowed range if tours_utils.is_initialized(month=month, year=year) or date_obj < current or date_obj > last_allowed: raise PermissionDenied # process form selected_days = request.POST.get("selected_days", None) if selected_days is None: return HttpResponseBadRequest # make a counter of all selected days (i.e., days on which to have tours) if selected_days != "": selected_days_counter = Counter([int(i) for i in selected_days.split(",")]) else: selected_days_counter = Counter() # make a counter of all days in the month month_dates_counter = Counter([i for i in calendar.Calendar().itermonthdays(year, month) if i != 0]) canceled_days_counter = month_dates_counter - selected_days_counter for num, times in canceled_days_counter.items(): date = datetime.date(year, month, num) canceled_day = CanceledDay(date=date) canceled_day.save() # add default tours on non-blacked out days default_tours = DefaultTour.objects.all() weeks = calendar.Calendar().monthdatescalendar(year, month) for week in weeks: for date in week: if date.month == month and not CanceledDay.objects.filter(date=date): for default_tour in default_tours.filter(day_num=date.weekday): add_tour = Tour.objects.create( source=default_tour.source, time=datetime.datetime( date.year, date.month, date.day, default_tour.hour, default_tour.minute ), notes=default_tour.notes, length=default_tour.length, default_tour=True, ) # mark month as initialized initialized_month = InitializedMonth.objects.create(month=month, year=year) return redirect("tours:month", month=month, year=year)
def test_encoder(): result = json.dumps({"now": now(), "context": "test"}, cls=JSONEncoder) assert isinstance(result, str) assert len(result) != 0