def test_force_locale(self): app = flask.Flask(__name__) b = babel.Babel(app) @b.localeselector def select_locale(): return 'de_DE' with app.test_request_context(): assert str(babel.get_locale()) == 'de_DE' with babel.force_locale('en_US'): assert str(babel.get_locale()) == 'en_US' assert str(babel.get_locale()) == 'de_DE'
def set_queries(self): pycountry_locale = gettext.translation( 'iso3166-2', pycountry.LOCALES_DIR, languages=[str(get_locale()), 'en']) countries = [(pycountry_locale.gettext(country.name), country.alpha_2) for country in pycountry.countries] countries.sort() self.country.choices = [(code, name) for (name, code) in countries]
def row_handler(row): dict_row = dict(list(zip(headers, row))) if dict_row.get('status') in INVOICE_STATUS.keys(): dict_row['status'] = INVOICE_STATUS.get(dict_row['status']) if isinstance(dict_row.get('invoiced_at'), datetime): dict_row['invoiced_at'] = format_datetime( localize_timezone(dict_row['invoiced_at']), format='long', locale=get_locale() or 'en') return dict_row
def row_handler(row): # localize datetime row_list = [ v if not isinstance(v, datetime) else format_datetime( localize_timezone(v), format='long', locale=get_locale()) for v in row ] # add assignee url access_token = row_list[assignee_url_index] if access_token: row_list[assignee_url_index] = url_for('line_items', access_token=access_token, _external=True) return row_list
def row_handler(row): # Convert row to a dict dict_row = {} for idx, item in enumerate(row): # 'assignee_details' is a dict already, so copy and include prefixes if idx == attendee_details_index and isinstance(item, dict): for key in item.keys(): dict_row['attendee_details_' + key] = item[key] # Item is a datetime object, so format and add to dict elif isinstance(item, datetime): dict_row[headers[idx]] = format_datetime( localize_timezone(item), format='long', locale=get_locale()) # Item is a string, add it to the dict with the corresponding key else: dict_row[headers[idx]] = item return dict_row
def datetime_filter( value: Union[datetime, date, time], format: str = 'medium', # NOQA: A002 # skipcq: PYL-W0622 locale: Union[Locale, str] = None, usertz: bool = True, ) -> str: """Render a localized date and time.""" dt: Union[datetime, date, time] if isinstance(value, datetime) and usertz: if value.tzinfo is None: dt = utc.localize(value).astimezone(get_timezone()) else: dt = value.astimezone(get_timezone()) else: dt = value return format_datetime( dt, format=format, locale=locale if locale else get_locale() or DEFAULT_LOCALE)
def row_handler(row): # Convert row to a dict dict_row = {} for idx, item in enumerate(row): # 'assignee_details' is a dict already, so copy and include prefixs if idx == attendee_details_index and isinstance(item, dict): for key in item.keys(): dict_row['attendee_details_' + key] = item[key] # Item is a datetime object, so format and add to dict elif isinstance(item, datetime): dict_row[headers[idx]] = format_datetime( localize_timezone(item), format='long', locale=get_locale() or 'en' ) # FIXME: How to handle locale where the accept langauges header isn't specified? Relevant issue in baseframe https://github.com/hasgeek/baseframe/issues/154 # Value is a string, add it to the dict with the corresponding key else: dict_row[headers[idx]] = item return dict_row
def timedelta_filter( delta: Union[int, timedelta, datetime], granularity: str = 'second', threshold: float = 0.85, add_direction: bool = False, format: str = 'long', # NOQA: A002 # skipcq: PYL-W0622 locale: Union[Locale, str] = None, ) -> str: """ Render a timedelta or int (representing seconds) as a duration. :param delta: A timedelta object representing the time difference to format, or the delta in seconds as an int value :param granularity: Determines the smallest unit that should be displayed, the value can be one of “year”, “month”, “week”, “day”, “hour”, “minute” or “second” :param threshold: Factor that determines at which point the presentation switches to the next higher unit :param add_direction: If this flag is set to True the return value will include directional information. For instance a positive timedelta will include the information about it being in the future, a negative will be information about the value being in the past. If a datetime is provided for delta, add_direction will be forced to True :param format: The format, can be “narrow”, “short” or “long” :param locale: A Locale object or a locale identifier (defaults to current locale) """ if isinstance(delta, datetime): # Convert datetimes into a timedelta from present and turn on add_direction if not delta.tzinfo: delta = utc.localize(delta) delta = delta - request_timestamp() add_direction = True return format_timedelta( delta, granularity=granularity, threshold=threshold, add_direction=add_direction, format=format, locale=locale if locale else get_locale() or DEFAULT_LOCALE, )
def calendar_weeks(self, leading_weeks=True): # session_dates is a list of tuples in this format - # (date, day_start_at, day_end_at, event_count) session_dates = list( db.session.query('date', 'day_start_at', 'day_end_at', 'count').from_statement( db.text(''' SELECT DATE_TRUNC('day', "start_at" AT TIME ZONE :timezone) AS date, MIN(start_at) as day_start_at, MAX(end_at) as day_end_at, COUNT(*) AS count FROM "session" WHERE "project_id" = :project_id AND "start_at" IS NOT NULL AND "end_at" IS NOT NULL GROUP BY date ORDER BY date; ''')).params(timezone=self.timezone.zone, project_id=self.id)) session_dates_dict = { date.date(): { 'day_start_at': day_start_at, 'day_end_at': day_end_at, 'count': count, } for date, day_start_at, day_end_at, count in session_dates } # FIXME: This doesn't work. This code needs to be tested in isolation # session_dates = db.session.query( # db.cast( # db.func.date_trunc('day', db.func.timezone(self.timezone.zone, Session.start_at)), # db.Date).label('date'), # db.func.count().label('count') # ).filter( # Session.project == self, # Session.scheduled # ).group_by(db.text('date')).order_by(db.text('date')) # if the project's week is within next 2 weeks, send current week as well now = utcnow().astimezone(self.timezone) current_week = Week.withdate(now) if leading_weeks and self.schedule_start_at is not None: schedule_start_week = Week.withdate(self.schedule_start_at) # session_dates is a list of tuples in this format - # (date, day_start_at, day_end_at, event_count) # as these days dont have any event, day_start/end_at are None, # and count is 0. if (schedule_start_week > current_week and (schedule_start_week - current_week) <= 2): if (schedule_start_week - current_week) == 2: # add this so that the next week's dates # are also included in the calendar. session_dates.insert( 0, (now + timedelta(days=7), None, None, 0)) session_dates.insert(0, (now, None, None, 0)) weeks = defaultdict(dict) today = now.date() for project_date, _day_start_at, _day_end_at, session_count in session_dates: weekobj = Week.withdate(project_date) if weekobj.week not in weeks: weeks[weekobj.week]['year'] = weekobj.year # Order is important, and we need dict to count easily weeks[weekobj.week]['dates'] = OrderedDict() for wdate in weekobj.days(): weeks[weekobj.week]['dates'].setdefault(wdate, 0) if project_date.date() == wdate: # If the event is over don't set upcoming for current week if wdate >= today and weekobj >= current_week and session_count > 0: weeks[weekobj.week]['upcoming'] = True weeks[weekobj.week]['dates'][wdate] += session_count if 'month' not in weeks[weekobj.week]: weeks[weekobj.week]['month'] = format_date( wdate, 'MMM', locale=get_locale()) # Extract sorted weeks as a list weeks_list = [v for k, v in sorted(weeks.items())] for week in weeks_list: # Convering to JSON messes up dictionary key order even though we used OrderedDict. # This turns the OrderedDict into a list of tuples and JSON preserves that order. week['dates'] = [{ 'isoformat': date.isoformat(), 'day': format_date(date, 'd', get_locale()), 'count': count, 'day_start_at': (session_dates_dict[date]['day_start_at'].astimezone( self.timezone).strftime('%I:%M %p') if date in session_dates_dict.keys() else None), 'day_end_at': (session_dates_dict[date]['day_end_at'].astimezone( self.timezone).strftime('%I:%M %p %Z') if date in session_dates_dict.keys() else None), } for date, count in week['dates'].items()] return { 'locale': get_locale(), 'weeks': weeks_list, 'today': now.date().isoformat(), 'days': [ format_date(day, 'EEE', locale=get_locale()) for day in Week.thisweek().days() ], }