Debian Codegraph @

docs/user-guide/examples.rst

raw
1
2 How to
3 ======
4
5 Additionally to the examples listed here, you can have a look the
6 `API documentation`_.
7 In the `Media Section`_, you can videos and useful information on social media.
8
9 .. _`API documentation`: ../reference/api.html
10 .. _`Media Section`: ../community/media.html
11
12 Read a file and print events
13 ----------------------------
14
15 The following example loads a calendar from a file and
16 prints the events happening between the 1st of January 2017 and the 1st of January 2018.
17
18 .. code-block:: python
19
20 >>> import icalendar
21 >>> import recurring_ical_events
22 >>> from pathlib import Path
23
24 # read the calendar file and parse it
25 # CALENDARS = Path("to/your/calendar/directory")
26 >>> calendar_file : Path = CALENDARS / "fablab_cottbus.ics"
27 >>> ical_string = calendar_file.read_bytes()
28 >>> print(ical_string[:28])
29 BEGIN:VCALENDAR
30 VERSION:2.0
31 >>> a_calendar = icalendar.Calendar.from_ical(ical_string)
32
33 # request the events in a specific interval
34 # start on the 1st of January 2017 0:00
35 >>> start_date = (2017, 1, 1)
36
37 # the event on the 1st of January 2018 is not included
38 >>> end_date = (2018, 1, 1)
39 >>> events = recurring_ical_events.of(a_calendar).between(start_date, end_date)
40 >>> for event in events:
41 ... start = event["DTSTART"].dt
42 ... summary = event["SUMMARY"]
43 ... print(f"start {start} summary {summary}")
44 start 2017-03-11 17:00:00+01:00 summary Vereinssitzung
45 start 2017-06-10 10:00:00+02:00 summary Repair und Recycling Café
46 start 2017-06-11 16:30:00+02:00 summary Brandenburger Maker-Treffen
47 start 2017-07-05 17:45:00+02:00 summary Der Computer-Treff fällt aus
48 start 2017-07-29 14:00:00+02:00 summary Sommerfest
49 start 2017-10-19 16:00:00+02:00 summary 3D-Modelle programmieren mit OpenSCAD
50 start 2017-10-20 16:00:00+02:00 summary Programmier dir deine eigene Crypto-Währung
51 start 2017-10-21 13:00:00+02:00 summary Programmiere deine eigene Wetterstation
52 start 2017-10-22 13:00:00+02:00 summary Luftqualität: Ein Workshop zum selber messen (Einsteiger)
53 start 2017-10-22 13:00:00+02:00 summary Websites selbst programmieren
54
55
56 List events at certain a time
57 -----------------------------
58
59 You can get all events which take place at ``a_date``.
60 A date can be a year, e.g. ``2023``, a month of a year e.g. January in 2023 ``(2023, 1)``, a day of a certain month e.g. ``(2023, 1, 1)``, an hour e.g. ``(2023, 1, 1, 0)``, a minute e.g. ``(2023, 1, 1, 0, 0)``, or second as well as a `datetime.date <https://docs.python.org/3/library/datetime.html#datetime.date>`_ object and `datetime.datetime <https://docs.python.org/3/library/datetime.html#datetime.datetime>`_.
61
62 The start and end are inclusive. As an example: if an event is longer than one day it is still included if it takes place at ``a_date``.
63
64 .. code-block:: python
65
66 >>> import datetime
67
68 # save the query object for the calendar
69 >>> query = recurring_ical_events.of(a_calendar)
70 >>> len(query.at(2023)) # a year - 2023 has 12 events happening
71 12
72 >>> len(query.at((2023,))) # a year
73 12
74 >>> len(query.at((2023, 1))) # January in 2023 - only one event is in January
75 1
76 >>> len(query.at((2023, 1, 1))) # the 1st of January in 2023
77 0
78 >>> len(query.at("20230101")) # the 1st of January in 2023
79 0
80 >>> len(query.at((2023, 1, 1, 0))) # the first hour of the year 2023
81 0
82 >>> len(query.at((2023, 1, 1, 0, 0))) # the first minute in 2023
83 0
84 >>> len(query.at(datetime.date(2023, 1, 1))) # the first day in 2023
85 0
86
87 The resulting ``events`` are a list of `icalendar events <https://icalendar.readthedocs.io/en/latest/api.html#icalendar.cal.Event>`_, see below.
88
89 List events within a time range
90 -------------------------------
91
92 ``between(start, end)`` returns all events happening between a start and an end time. Both arguments can be `datetime.datetime`_, `datetime.date`_, tuples of numbers passed as arguments to `datetime.datetime`_ or strings in the form of
93 ``%Y%m%d`` (``yyyymmdd``) and ``%Y%m%dT%H%M%SZ`` (``yyyymmddThhmmssZ``).
94 Additionally, the ``end`` argument can be a ``datetime.timedelta`` to express that the end is relative to the ``start``.
95 For examples of arguments, see ``at(a_date)`` above.
96
97 .. code-block:: python
98
99 >>> query = recurring_ical_events.of(a_calendar)
100
101 # What happens in 2016, 2017 and 2018?
102 >>> events = recurring_ical_events.of(a_calendar).between(2016, 2019)
103 >>> len(events) # quite a lot is happening!
104 39
105
106 The resulting ``events`` are in a list of `icalendar events`_, see below.
107
108 List events after a certain time
109 --------------------------------
110
111 You can retrieve events that happen after a time or date using ``after(earliest_end)``.
112 Events that are happening during the ``earliest_end`` are included in the iteration.
113
114 .. code-block:: python
115
116 >>> earlierst_end = 2023
117 >>> for i, event in enumerate(query.after(earlierst_end)):
118 ... print(f"{event['SUMMARY']} ends {event['DTEND'].dt}") # all dates printed are after January 1st 2023
119 ... if i > 10: break # we might get endless events and a lot of them!
120 Repair Café ends 2023-01-07 17:00:00+01:00
121 Repair Café ends 2023-02-04 17:00:00+01:00
122 Repair Café ends 2023-03-04 17:00:00+01:00
123 Repair Café ends 2023-04-01 17:00:00+02:00
124 Repair Café ends 2023-05-06 17:00:00+02:00
125 Repair Café ends 2023-06-03 17:00:00+02:00
126 Repair Café ends 2023-07-01 17:00:00+02:00
127 Repair Café ends 2023-08-05 17:00:00+02:00
128 Repair Café ends 2023-09-02 17:00:00+02:00
129 Repair Café ends 2023-10-07 17:00:00+02:00
130 Repair Café ends 2023-11-04 17:00:00+01:00
131 Repair Café ends 2023-12-02 17:00:00+01:00
132
133
134 List all events
135 ---------------
136
137 If you wish to iterate over all occurrences of the components, then you can use ``all()``.
138 Since a calendar can define a huge amount of recurring entries, this method generates them
139 and forgets them, reducing memory overhead.
140
141 This example shows the first event that takes place in the calendar:
142
143 .. code-block:: python
144
145 >>> first_event = next(query.all()) # not all events are generated
146 >>> print(f"The first event is {first_event['SUMMARY']}")
147 The first event is Weihnachts Repair-Café
148
149 Count events
150 ------------
151
152 You can count occurrences of events and other components using ``count()``.
153
154 .. code-block:: python
155
156 >>> number_of_TODOs = recurring_ical_events.of(a_calendar, components=["VTODO"]).count()
157 >>> print(f"You have {number_of_TODOs} things to do!")
158 You have 0 things to do!
159
160 >>> number_of_journal_entries = recurring_ical_events.of(a_calendar, components=["VJOURNAL"]).count()
161 >>> print(f"There are {number_of_journal_entries} journal entries in the calendar.")
162 There are 0 journal entries in the calendar.
163
164 However, this can be very costly!
165
166 Split a query into pages
167 ------------------------
168
169 Pagination allows you to chop the resulting components into chunks of a certain size.
170
171 .. code-block:: python
172
173 # we get a calendar with 10 events and 2 events per page
174 >>> ten_events = recurring_ical_events.example_calendar("event_10_times")
175 >>> pages = recurring_ical_events.of(ten_events).paginate(2)
176
177 # we can iterate over the pages with 2 events each
178 >>> for i, last_page in enumerate(pages):
179 ... print(f"page: {i}")
180 ... for event in last_page:
181 ... print(f"-> {event.start}")
182 ... if i == 1: break
183 page: 0
184 -> 2020-01-13 07:45:00+01:00
185 -> 2020-01-14 07:45:00+01:00
186 page: 1
187 -> 2020-01-15 07:45:00+01:00
188 -> 2020-01-16 07:45:00+01:00
189
190 If you run a web service and you would like to continue pagination after a certain page,
191 this can be done, too. Just hand someone the ``next_page_id`` and continue from there on.
192
193 .. code-block:: python
194
195 # resume the same query from the next page
196 >>> pages = recurring_ical_events.of(ten_events).paginate(2, next_page_id = last_page.next_page_id)
197 >>> for i, last_page in enumerate(pages):
198 ... print(f"page: {i + 2}")
199 ... for event in last_page:
200 ... print(f"-> {event.start}")
201 ... if i == 1: break
202 page: 2
203 -> 2020-01-17 07:45:00+01:00
204 -> 2020-01-18 07:45:00+01:00
205 page: 3
206 -> 2020-01-19 07:45:00+01:00
207 -> 2020-01-20 07:45:00+01:00
208
209 The ``last_page.next_page_id`` is a string so that it can be used easily.
210 It is tested against malicious modification and can safely be passed from a third party source.
211
212 Additionally to the page size, you can also pass a ``start`` and an ``end`` to the pages so that
213 all components are visible within that time.
214
215 Get Todos and Journal entries
216 -----------------------------
217
218 By default the ``recurring_ical_events`` only selects events as the name already implies.
219 However, there are different `components <https://icalendar.readthedocs.io/en/latest/api.html#icalendar.cal.Component>`_ available in a `calendar <https://icalendar.readthedocs.io/en/latest/api.html#icalendar.cal.Calendar>`_.
220 You can select which components you like to have returned by passing ``components`` to the ``of`` function:
221
222 .. code-block:: python
223
224 of(a_calendar, components=["VEVENT"])
225
226 Here is a template code for choosing the supported types of components:
227
228 .. code-block:: python
229
230 >>> query_events = recurring_ical_events.of(a_calendar)
231 >>> query_journals = recurring_ical_events.of(a_calendar, components=["VJOURNAL"])
232 >>> query_todos = recurring_ical_events.of(a_calendar, components=["VTODO"])
233 >>> query_all = recurring_ical_events.of(a_calendar, components=["VTODO", "VEVENT", "VJOURNAL"])
234
235 If a type of component is not listed here, it can be added.
236 Please create an issue for this in the source code repository.
237
238 For further customization, please refer to the section on how to extend the default functionality.
239
240 Calculate Alarm times
241 ---------------------
242
243 Alarms are subcomponents of events and todos. They only make sense with an event or todo.
244 Thus the interface is slightly different.
245
246 Add ``VALARM`` as the component you would like:
247
248 .. code-block:: python
249
250 >>> query_alarms = recurring_ical_events.of(a_calendar, components=["VALARM"])
251
252 In the following example, an event has an alarm one week before it starts.
253 The component returned is not a ``VALARM`` component but instead the ``VEVENT`` with only
254 one ``VALARM`` in it.
255
256 .. code-block:: python
257
258 # read an .ics file with an event with an alarm
259 >>> calendar_with_alarm = recurring_ical_events.example_calendar("alarm_1_week_before_event")
260 >>> alarm_day = datetime.date(2024, 12, 2)
261
262 # we get the event that has an alarm on that day
263 >>> event = recurring_ical_events.of(calendar_with_alarm, components=["VALARM"]).at(alarm_day)[0]
264 >>> len(event.alarms.times)
265 1
266 >>> alarm = event.alarms.times[0]
267
268 # the alarm happens one week before the event
269 >>> event.start - alarm.trigger
270 datetime.timedelta(days=7)
271
272 In the following code, we query the same day for a ``VEVENT`` component and we find nothing.
273 The event happens a week later.
274
275 .. code-block:: python
276
277 # No events on that day. There is only an alarm.
278 >>> recurring_ical_events.of(calendar_with_alarm, components=["VEVENT"]).at(alarm_day)
279 []
280
281 When querying events and todos, they keep their alarms and other subcompnents.
282 These alarm times can be outside of the dates requested.
283
284 In this example, we get an event and find that it has several alarms in it.
285
286 .. code-block:: python
287
288 >>> event_day = alarm_day + datetime.timedelta(days=7)
289 >>> event = recurring_ical_events.of(calendar_with_alarm, components=["VEVENT"]).at(event_day)[0]
290
291 # The event a week later has more than one alarm.
292 >>> len(event.walk("VALARM"))
293 2
294
295
296 Edit one event of an existing series
297 ------------------------------------
298
299 Editing one event of a series is necessary for calendar invites e.g. via email.
300
301 Below, you see how to edit an event that occurs in a series.
302 It is important that you increase the `sequence number <https://www.rfc-editor.org/rfc/rfc5545#section-3.8.7.4>`_
303 of the event to indicate the new version.
304
305 .. code-block:: python
306
307 >>> calendar = recurring_ical_events.example_calendar("recurring_events_moved")
308 >>> event = recurring_ical_events.of(calendar).at("20190309")[0]
309
310 # This event happens on 2019-03-09.
311 >>> print(event["SUMMARY"])
312 New Event
313
314 # The event can be modified.
315 >>> event["SUMMARY"] = "Modified Again!"
316
317 # Make sure to increase the sequence number!
318 # If you do not do that, the modification will not appear.
319 >>> event["SEQUENCE"] = event.get("SEQUENCE", 0) + 1
320
321 # Add the modified event to the calendar to replace the original.
322 >>> calendar.add_component(event)
323
324 # Get the day again and see the modified event.
325 >>> event = recurring_ical_events.of(calendar).at("20190309")[0]
326 >>> print(event["SUMMARY"])
327 Modified Again!
328
329
330 Extend ``recurring-ical-events``
331 --------------------------------
332
333 All the functionality of ``recurring-ical-events`` can be extended and modified.
334 To understand where to extend, have a look at the `Architecture <../reference/architecture.html>`_.
335
336 The first place for extending is the collection of components.
337 Components are collected into a ``Series``.
338 A series belongs together because all components have the same ``UID``.
339 In this example, we collect one VEVENT which matches a certain UID:
340
341 .. code-block:: python
342
343 >>> from recurring_ical_events import SelectComponents, EventAdapter, Series
344 >>> from icalendar.cal import Component
345 >>> from typing import Sequence
346
347 # create the calendar
348 >>> calendar_file = CALENDARS / "machbar_16_feb_2019.ics"
349 >>> machbar_calendar = icalendar.Calendar.from_ical(calendar_file.read_bytes())
350
351 # Create a collector of components that searches for an event with a specific UID
352 >>> class CollectOneUIDEvent(SelectComponents):
353 ... def __init__(self, uid:str) -> None:
354 ... self.uid = uid
355 ... def collect_series_from(self, source: Component, suppress_errors: tuple) -> Sequence[Series]:
356 ... components : list[Component] = []
357 ... for component in source.walk("VEVENT"):
358 ... if component.get("UID") == self.uid:
359 ... components.append(EventAdapter(component))
360 ... return [Series(components)] if components else []
361
362 # collect only one UID: [email protected]
363 >>> one_uid = CollectOneUIDEvent("[email protected]")
364 >>> uid_query = recurring_ical_events.of(machbar_calendar, components=[one_uid])
365 >>> uid_query.count() # the event has no recurrence and thus there is only one
366 1
367
368 Several ways of extending the functionality have been created to override internals.
369 These can be subclassed or composed.
370
371 Below, you can choose to collect all components. Subclasses can be created for the
372 ``Series`` and the ``Occurrence``.
373
374 .. code-block:: python
375
376 >>> from recurring_ical_events import AllKnownComponents, Series, Occurrence
377
378 # we create a calendar with one event
379 >>> calendar_file = CALENDARS / "one_event.ics"
380 >>> one_event = icalendar.Calendar.from_ical(calendar_file.read_bytes())
381
382 # You can override the Occurrence and Series classes for all computable components
383 >>> select_all_known = AllKnownComponents(series=Series, occurrence=Occurrence)
384 >>> select_all_known.names # these are the supported types of components
385 ['VALARM', 'VEVENT', 'VJOURNAL', 'VTODO']
386 >>> query_all_known = recurring_ical_events.of(one_event, components=[select_all_known])
387
388 # There should be exactly one event.
389 >>> query_all_known.count()
390 1
391
392 This example shows that the behavior for specific types of components can be extended.
393 Additional to the series, you can change the ``ComponentAdapter`` that provides
394 a unified interface for all the components with the same name (``VEVENT`` for example).
395
396 .. code-block:: python
397
398 >>> from recurring_ical_events import ComponentsWithName, EventAdapter, JournalAdapter, TodoAdapter
399
400 # You can also choose to select only specific subcomponents by their name.
401 # The default arguments are added to show the extensibility.
402 >>> select_events = ComponentsWithName("VEVENT", adapter=EventAdapter, series=Series, occurrence=Occurrence)
403 >>> select_todos = ComponentsWithName("VTODO", adapter=TodoAdapter, series=Series, occurrence=Occurrence)
404 >>> select_journals = ComponentsWithName("VJOURNAL", adapter=JournalAdapter, series=Series, occurrence=Occurrence)
405
406 # There should be one event happening and nothing else
407 >>> recurring_ical_events.of(one_event, components=[select_events]).count()
408 1
409 >>> recurring_ical_events.of(one_event, components=[select_todos]).count()
410 0
411 >>> recurring_ical_events.of(one_event, components=[select_journals]).count()
412 0
413
414 So, if you would like to modify all events that are returned by the query,
415 you can do that subclassing the ``Occurrence`` class.
416
417
418 .. code-block:: python
419
420 # This occurence changes adds a new attribute to the resulting events
421 >>> class MyOccurrence(Occurrence):
422 ... """An occurrence that modifies the component."""
423 ... def as_component(self, keep_recurrence_attributes: bool) -> Component:
424 ... """Return a shallow copy of the source component and modify some attributes."""
425 ... component = super().as_component(keep_recurrence_attributes)
426 ... component["X-MY-ATTRIBUTE"] = "my occurrence"
427 ... return component
428 >>> query = recurring_ical_events.of(one_event, components=[ComponentsWithName("VEVENT", occurrence=MyOccurrence)])
429 >>> event = next(query.all())
430 >>> event["X-MY-ATTRIBUTE"]
431 'my occurrence'
432
433 This library allows extension of functionality during the selection of components to calculate using these classes:
434
435 * ``ComponentsWithName`` - for components of a certain name
436 * ``AllKnownComponents`` - for all components known
437 * ``SelectComponents`` - the interface to provide
438
439 You can further customize behaviour by subclassing these:
440
441 * ``ComponentAdapter`` such as ``EventAdapter``, ``JournalAdapter`` or ``TodoAdapter``.
442 * ``Series``
443 * ``Occurrence``
444 * ``CalendarQuery``
445
446
447 Increase Performance
448 --------------------
449
450 If you use :meth:`recurring_ical_events.CalendarQuery.between` and other queries
451 several times, it is faster to re-use the object coming from :func:`recurring_ical_events.of`.
452
453 .. code-block:: python
454
455 >>> query = recurring_ical_events.of(a_calendar)
456 >>> events_of_day_1 = query.at((2019, 2, 1))
457 >>> events_of_day_2 = query.at((2019, 2, 2))
458 >>> events_of_day_3 = query.at((2019, 2, 3))
459
460 # ... and so on
461
462
463 Skip badly formatted ical events
464 --------------------------------
465
466 Some events may be badly formatted and therefore cannot be handled by ``recurring-ical-events``.
467 Passing ``skip_bad_series=True`` as ``of()`` argument will totally skip theses events.
468
469 .. code-block:: python
470
471 # Create a calendar that contains broken events.
472 >>> calendar_file = CALENDARS / "bad_rrule_missing_until_event.ics"
473 >>> calendar_with_bad_event = icalendar.Calendar.from_ical(calendar_file.read_bytes())
474
475 # By default, broken events result in errors.
476 >>> recurring_ical_events.of(calendar_with_bad_event, skip_bad_series=False).count()
477 Traceback (most recent call last):
478 ...
479 recurring_ical_events.errors.BadRuleStringFormat: UNTIL parameter is missing: FREQ=WEEKLY;BYDAY=TH;WKST=SU;UNTL=20191023
480
481 # With skip_bad_series=True we skip the series that we cannot handle.
482 >>> recurring_ical_events.of(calendar_with_bad_event, skip_bad_series=True).count()
483 0