当前位置: 首页>>代码示例>>Python>>正文


Python icalendar.Calendar方法代码示例

本文整理汇总了Python中icalendar.Calendar方法的典型用法代码示例。如果您正苦于以下问题:Python icalendar.Calendar方法的具体用法?Python icalendar.Calendar怎么用?Python icalendar.Calendar使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在icalendar的用法示例。


在下文中一共展示了icalendar.Calendar方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: write

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Calendar [as 别名]
def write(self, outfile, encoding):
        """
        Writes the feed to the specified file in the
        specified encoding.
        """
        cal = Calendar()
        cal.add("version", "2.0")
        cal.add("calscale", "GREGORIAN")

        for ifield, efield in FEED_FIELD_MAP:
            val = self.feed.get(ifield)
            if val is not None:
                cal.add(efield, val)

        self.write_items(cal)

        to_ical = getattr(cal, "as_string", None)
        if not to_ical:
            to_ical = cal.to_ical
        outfile.write(to_ical()) 
开发者ID:jazzband,项目名称:django-ical,代码行数:22,代码来源:feedgenerator.py

示例2: write_ical

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Calendar [as 别名]
def write_ical(events, year, dataDir):
    # write iCal
    cal = Calendar()

    for awesomeEvent in events:
        event = Event()

        event.add('summary', awesomeEvent.title)
        event.add('dtstart', date.fromisoformat(awesomeEvent.startDate))
        event.add('dtend', date.fromisoformat(
            awesomeEvent.endDate) + timedelta(days=1))
        event.add('description',
                  f'{awesomeEvent.description} - {awesomeEvent.url}')
        event.add('location', awesomeEvent.location)
        cal.add_component(event)

    with open(f'{dataDir}{year}.ics', 'wb') as ics:
        ics.write(cal.to_ical()) 
开发者ID:ildoc,项目名称:awesome-italy-events,代码行数:20,代码来源:generate_data.py

示例3: calendar

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Calendar [as 别名]
def calendar(request):
    """
    Calendar display: all the hard work is JS/AJAX.
    """
    #user = get_object_or_404(Person, userid=request.user.username)
    context = {}
    return render(request, "dashboard/calendar.html", context) 
开发者ID:sfu-fas,项目名称:coursys,代码行数:9,代码来源:views.py

示例4: create_calendar_url

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Calendar [as 别名]
def create_calendar_url(request):
    user = get_object_or_404(Person, userid=request.user.username)
    config = _get_calendar_config(user)
    if request.method == 'POST':
        form = FeedSetupForm(request.POST)
        if form.is_valid():
            token = new_feed_token()
            config['token'] = token
            uc = UserConfig.objects.filter(user=user, key="calendar-config")
            if uc:
                uc = uc[0]
                uc.value = config
            else:
                uc = UserConfig(user=user, key="calendar-config", value=config)
            uc.save()
            messages.add_message(request, messages.SUCCESS, 'Calendar URL configured.')
            return HttpResponseRedirect(reverse('config:config'))
    else:
        if 'token' in config:
            # pre-check if we're changing the token
            form = FeedSetupForm({'agree': True})
        else:
            form = FeedSetupForm()

    context = {'form': form}
    return render(request, "dashboard/calendar_url.html", context) 
开发者ID:sfu-fas,项目名称:coursys,代码行数:28,代码来源:views.py

示例5: to_ical

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Calendar [as 别名]
def to_ical(self, encoding='utf-8', **kwargs):
		"""
		Convert the calendar object to a string in the iCalendar format.

		:return: The string representation of the data.
		:rtype: str
		"""
		return super(Calendar, self).to_ical(**kwargs).decode('utf-8') 
开发者ID:rsmusllp,项目名称:king-phisher,代码行数:10,代码来源:ics.py

示例6: generate_icalendar_element

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Calendar [as 别名]
def generate_icalendar_element(event):
    icalendar_event = CalendarEvent()
    if event.start_time:
        icalendar_event.add('dtstart', event.start_time)
    if event.end_time:
        icalendar_event.add('dtend', event.end_time)
    if event.name_en:
        icalendar_event.add('summary', event.name_en)

    cal = Calendar()
    cal.add('version', '2.0')
    cal.add('prodid', '-//events.hel.fi//NONSGML Feeder//EN')
    cal.add_component(icalendar_event)

    term = None
    if event.start_time and event.end_time:
        term = "open"
    elif event.start_time:
        term = "open"
    elif event.end_time:
        term = "close"

    if term:
        return {
            "term": "open",
            "value": cal.to_ical().decode('utf8'),
            "type": "text/icalendar"
        }
    else:
        return None 
开发者ID:City-of-Helsinki,项目名称:linkedevents,代码行数:32,代码来源:city_sdk.py

示例7: schedule2calendar

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Calendar [as 别名]
def schedule2calendar(schedule, name='课表', using_todo=True):
    """
    将上课时间表转换为 icalendar

    :param schedule: 上课时间表
    :param name: 日历名称
    :param using_todo: 使用 ``icalendar.Todo`` 而不是 ``icalendar.Event`` 作为活动类
    :return: icalendar.Calendar()
    """
    # https://zh.wikipedia.org/wiki/ICalendar
    # http://icalendar.readthedocs.io/en/latest
    # https://tools.ietf.org/html/rfc5545
    cal = icalendar.Calendar()
    cal.add('X-WR-TIMEZONE', 'Asia/Shanghai')
    cal.add('X-WR-CALNAME', name)
    cls = icalendar.Todo if using_todo else icalendar.Event
    for week, start, end, data in schedule:
        # "事件"组件更具通用性, Google 日历不支持"待办"组件
        item = cls(
            SUMMARY='第{:02d}周-{}'.format(week, data),
            DTSTART=icalendar.vDatetime(start),
            DTEND=icalendar.vDatetime(end),
            DESCRIPTION='起始于 {}, 结束于 {}'.format(start.strftime('%H:%M'), end.strftime('%H:%M'))
        )
        now = datetime.now()
        # 这个状态"事件"组件是没有的, 对于待办列表类应用有作用
        # https://tools.ietf.org/html/rfc5545#section-3.2.12
        if using_todo:
            if start < now < end:
                item.add('STATUS', 'IN-PROCESS')
            elif now > end:
                item.add('STATUS', 'COMPLETED')
        cal.add_component(item)
    return cal 
开发者ID:elonzh,项目名称:hfut,代码行数:36,代码来源:curriculum_calendar.py

示例8: get

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Calendar [as 别名]
def get(self, request, *args, **kwargs):
        document_id = request.GET.get('document_id')
        if not document_id:
            return JsonResponse({'error': "Document id is not defined."})

        sample_length = 100
        # Create calendar
        cal = icalendar.Calendar()
        cal.add('prodid', 'ContraxSuite (https://contraxsuite.com)')
        cal.add('version', settings.VERSION_NUMBER)

        # Filter to text unit
        for du in self.get_queryset():
            event = icalendar.Event()
            event.add("summary", "Calendar reminder for document {0}, text unit {1}:\n{2}"
                      .format(du.text_unit.document.name, du.text_unit_id,
                              du.text_unit.text[:sample_length]))
            event.add("dtstart", du.date)
            event.add("dtend", du.date)
            event.add("dtstamp", du.date)
            cal.add_component(event)

        filename = "document-{0}.ics".format(document_id)

        response = HttpResponse(cal.to_ical(), content_type='text/calendar; charset=utf8')
        response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
        return response


# --------------------------------------------------------
# Date Duration Usage Views
# -------------------------------------------------------- 
开发者ID:LexPredict,项目名称:lexpredict-contraxsuite,代码行数:34,代码来源:v1.py

示例9: get

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Calendar [as 别名]
def get(self, request, *args, **kwargs):
        document_pk = request.GET.get('document_pk')
        if not document_pk:
            return Http404("Document pk is not defined.")

        sample_length = 100
        # Create calendar
        cal = icalendar.Calendar()
        cal.add('prodid', 'ContraxSuite (https://contraxsuite.com)')
        cal.add('version', '1.0.3')

        # Filter to text unit
        for du in self.get_json_data()['data']:
            event = icalendar.Event()
            event.add("summary", "Calendar reminder for document {0}, text unit {1}:\n{2}"
                      .format(du['document__name'], du['text_unit_id'],
                              du['text_unit__textunittext__text'][:sample_length]))
            event.add("dtstart", du['date'])
            event.add("dtend", du['date'])
            event.add("dtstamp", du['date'])
            cal.add_component(event)

        filename = "document-{0}.ics".format(document_pk)

        response = HttpResponse(cal.to_ical(), content_type='text/calendar; charset=utf8')
        response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
        return response 
开发者ID:LexPredict,项目名称:lexpredict-contraxsuite,代码行数:29,代码来源:views.py

示例10: _collect_recurrence_changes

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Calendar [as 别名]
def _collect_recurrence_changes(calendar: icalendar.Calendar) -> ChangeMapping:
    ConcreteChangeMapping = Dict[str, List[icalendar.cal.Event]]  # noqa
    recurring_changes = {}  # type: ConcreteChangeMapping
    for component in calendar.walk():
        if component.name != "VEVENT":
            continue
        if component.get("recurrence-id"):
            if component.get("uid") not in recurring_changes:
                recurring_changes[component.get("uid")] = []
            recurring_changes[component.get("uid")].append(component)
    return recurring_changes 
开发者ID:languitar,项目名称:autosuspend,代码行数:13,代码来源:ical.py

示例11: get_calendar

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Calendar [as 别名]
def get_calendar(assessment):
    """
    Returns a compiled calendar containing the given assessment.
    """
    calendar = Calendar()
    for assessment_item in assessment:
        course, task, due_date, weight = assessment_item
        event = Event()
        event['uid'] = str(uuid())
        event['summary'] = f'{course} ({weight}): {task}'
        try:
            start_datetime, end_datetime = get_parsed_assessment_due_date(assessment_item)
        except DateSyntaxException as e:
            bot.logger.error(e.message)
            # If we can't parse a date, set its due date to today
            # and let the user know through its summary.
            # TODO(mitch): Keep track of these instances to attempt to accurately
            # parse them in future. Will require manual detection + parsing.
            start_datetime = end_datetime = datetime.today()
            event['summary'] = ("WARNING: DATE PARSING FAILED\n"
                                "Please manually set date for event!\n"
                                "The provided due date from UQ was"
                                + f" '{due_date}\'. {event['summary']}")
        event.add('dtstart', start_datetime)
        event.add('dtend', end_datetime)
        calendar.add_component(event)
    return calendar.to_ical() 
开发者ID:UQComputingSociety,项目名称:uqcsbot,代码行数:29,代码来源:calendar.py

示例12: _as_ics

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Calendar [as 别名]
def _as_ics(self, citymeo=False):
        if not self.initialized:
            self._lazy_init()
        cal = iCalendar()
        cal.add('prodid', '-//PonyConf.io//PonyConf//FR')
        cal.add('version', '2.0')
        cal.add('x-wr-calname', self.conference.name)
        cal.add('x-wr-timezone', settings.TIME_ZONE)
        cal.add('calscale', 'GREGORIAN')
        talks = self.talks
        if citymeo and talks.exists():
            talks = talks.filter(start_date__gte=now()-timedelta(minutes=5))
            if talks.exists():
                limit = talks.first().start_date.replace(hour=23, minute=59, second=59)
                talks = talks.filter(start_date__lte=limit)
        for talk in talks:
            event = iEvent()
            event.add('dtstart', talk.start_date)
            if not talk.end_date:
                continue
            event.add('dtend', talk.end_date)
            event.add('dtstamp', talk.updated)
            event.add('summary', talk.title)
            if talk.room:
                event.add('location', talk.room)
            event.add('status', 'CONFIRMED' if talk.accepted else 'TENTATIVE')
            if not citymeo:
                event.add('description', talk.description)
            event.add('uid', '%s/%s' % (self.site.domain, talk.id))
            cal.add_component(event)
        return cal.to_ical() 
开发者ID:PonyConf,项目名称:PonyConf,代码行数:33,代码来源:planning.py

示例13: generate

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Calendar [as 别名]
def generate(name: str, cards: Dict[Tuple[int, int], List[Dict]], semester: Semester, filename: str) -> None:
    """
    生成 ics 文件并保存到目录

    :param name: 姓名
    :param cards: 参与的课程
    :param semester: 当前导出的学期
    :param filename: 输出的文件名称,带后缀
    :return: None
    """
    from everyclass.server import statsd

    with tracer.trace("calendar_init"):
        semester_string = semester.to_str(simplify=True)
        semester = semester.to_tuple()

        # 创建 calender 对象
        cal = Calendar()
        cal.add('prodid', '-//Admirable//EveryClass//EN')
        cal.add('version', '2.0')
        cal.add('calscale', 'GREGORIAN')
        cal.add('method', 'PUBLISH')
        cal.add('X-WR-CALNAME', name + '的' + semester_string + '课表')
        cal.add('X-WR-TIMEZONE', 'Asia/Shanghai')

        # 时区
        tzc.add_component(tzs)
        cal.add_component(tzc)

    with tracer.trace("add_events"):
        # 创建 events
        for time in range(1, 7):
            for day in range(1, 8):
                if (day, time) in cards:
                    for card in cards[(day, time)]:
                        for week in card['week']:
                            dtstart = _get_datetime(week, day, get_time(time)[0], semester)
                            dtend = _get_datetime(week, day, get_time(time)[1], semester)

                            if dtstart.year == 1984:
                                continue

                            cal.add_component(_build_event(card_name=card['name'],
                                                           times=(dtstart, dtend),
                                                           classroom=card['classroom'],
                                                           teacher=card['teacher'],
                                                           week_string=card['week_string'],
                                                           current_week=week,
                                                           cid=card['cid']))

    with tracer.trace("write_file"):
        with open(os.path.join(calendar_dir(), filename), 'wb') as f:
            data = cal.to_ical()
            statsd.histogram('calendar.ics.generate.size', len(data))
            f.write(data) 
开发者ID:everyclass,项目名称:everyclass-server,代码行数:57,代码来源:ics_generator.py

示例14: calendar_ical

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Calendar [as 别名]
def calendar_ical(request, token, userid):
    """
    Return an iCalendar for this user, authenticated by the token in the URL
    """
    local_tz = pytz.timezone(settings.TIME_ZONE)
    utc = pytz.utc
    user = get_object_or_404(Person, userid=userid)
    
    # make sure the token in the URL (32 hex characters) matches the token stored in the DB
    config = _get_calendar_config(user)
    if 'token' not in config or config['token'] != token:
        # no token set or wrong token provided
        return NotFoundResponse(request)
    #else:
        # authenticated

    now = datetime.datetime.now()
    start = local_tz.localize(now - datetime.timedelta(days=180))
    end = local_tz.localize(now + datetime.timedelta(days=365))
    
    cal = Calendar()
    cal.add('version', '2.0')
    cal.add('prodid', '-//SFU CourSys//courses.cs.sfu.ca//')
    cal.add('X-PUBLISHED-TTL', 'PT1D')
    
    for data in _calendar_event_data(user, start, end, local_tz, dt_string=False):
        e = Event()
        e['uid'] = str(data['id'])
        e.add('summary', data['title'])
        e.add('dtstart', _ical_datetime(utc, data['start']))
        e.add('dtend', _ical_datetime(utc, data['end']))
        if data['category'] in ('DUE', 'HOLIDAY'):
            # these shouldn't be "busy" on calendars
            e.add('transp', 'TRANSPARENT')
        else:
            e.add('transp', 'OPAQUE')

        # spec says no TZID on UTC times
        if 'TZID' in e['dtstart'].params:
            del e['dtstart'].params['TZID']
        if 'TZID' in e['dtend'].params:
            del e['dtend'].params['TZID']
        
        e.add('categories', data['category'])
        if 'url' in data:
            e.add('url', data['url'])
        if 'location' in data:
            e.add('location', data['location'])
        cal.add_component(e)

    resp = HttpResponse(cal.to_ical(), content_type="text/calendar")
    return resp 
开发者ID:sfu-fas,项目名称:coursys,代码行数:54,代码来源:views.py

示例15: ical_from_pairings_list

# 需要导入模块: import icalendar [as 别名]
# 或者: from icalendar import Calendar [as 别名]
def ical_from_pairings_list(self, pairings, calendar_title, uid_component):
        cal = Calendar()
        cal.add('prodid', '-//{}//www.lichess4545.com//'.format(calendar_title))
        cal.add('version', '2.0')

        has_league = hasattr(self, 'league')
        league = self.league if has_league else None

        for pairing in pairings:
            if not has_league:
                round_ = pairing.get_round()
                if not round_:
                    continue
                league = round_.season.league
            time_control_seconds = league.time_control_total()
            if time_control_seconds:
                game_duration = timedelta(seconds=time_control_seconds * 2)
            else:
                game_duration = timedelta(hours=3)

            ical_event = Event()
            ical_event.add('summary', '{} vs {}'.format(
                pairing.white.lichess_username,
                pairing.black.lichess_username,
            ))
            ical_event.add('dtstart', pairing.scheduled_time)
            ical_event.add('dtend', pairing.scheduled_time + game_duration)
            ical_event.add('dtstamp', pairing.scheduled_time + game_duration)
            ical_event['uid'] = 'lichess4545.{}.events.{}'.format(
                uid_component,
                pairing.id,
            )
            cal.add_component(ical_event)

        response = HttpResponse(cal.to_ical(), content_type="text/calendar")
        response['Content-Disposition'] = 'attachment; filename={}.ics'.format(
            slugify(calendar_title)
        )
        return response


# -------------------------------------------------------------------------------
# Actual views 
开发者ID:cyanfish,项目名称:heltour,代码行数:45,代码来源:views.py


注:本文中的icalendar.Calendar方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。