Source code for town6.api

from __future__ import annotations

from onegov.event.collections import OccurrenceCollection
from onegov.api import ApiEndpoint
from onegov.gis import Coordinates


from typing import Any
from typing import TYPE_CHECKING

from onegov.org.models.page import NewsCollection

if TYPE_CHECKING:
    from onegov.org.models.page import News
    from onegov.town6.app import TownApp
    from onegov.event.models import Occurrence
    from onegov.core.orm.mixins import ContentMixin
    from onegov.core.orm.mixins import TimestampMixin
    from typing import TypeVar

[docs] T = TypeVar('T')
[docs] def get_geo_location(item: ContentMixin) -> dict[str, Any]: geo = item.content.get('coordinates', Coordinates()) or Coordinates() return {'lon': geo.lon, 'lat': geo.lat, 'zoom': geo.zoom}
[docs] def get_modified_iso_format(item: TimestampMixin) -> str: """ Returns the iso format of the modified or created field of item. :param item: db item e.g. agency, people, membership :return: str iso representation of item last modification """ return item.last_change.isoformat()
[docs] class EventApiEndpoint( ApiEndpoint['Occurrence'], ):
[docs] app: TownApp
[docs] endpoint = 'events'
@property
[docs] def collection(self) -> Any: result = OccurrenceCollection( self.session, page=self.page or 0 ) result.batch_size = self.batch_size return result
[docs] def item_data(self, item: Occurrence) -> dict[str, Any]: return { 'title': item.title, 'description': item.event.description, 'organizer': item.event.organizer, 'organizer_email': item.event.organizer_email, 'organizer_phone': item.event.organizer_phone, 'external_event_url': item.event.external_event_url, 'event_registration_url': item.event.event_registration_url, 'price': item.event.price, 'tags': item.event.tags, 'start': item.start.isoformat(), 'end': item.end.isoformat(), 'location': item.location, 'coordinates': get_geo_location(item), 'created': item.created.isoformat(), 'modified': get_modified_iso_format(item), }
[docs] class NewsApiEndpoint( ApiEndpoint['News'], ):
[docs] app: TownApp
[docs] endpoint = 'news'
[docs] filters = set()
@property
[docs] def collection(self) -> Any: result = NewsCollection( self.session, page=self.page or 0 ) result.batch_size = 25 return result
[docs] def item_data(self, item: News) -> dict[str, Any]: if item.publication_start: publication_start = item.publication_start.isoformat() else: publication_start = None if item.publication_end: publication_end = item.publication_end.isoformat() else: publication_end = None return { 'title': item.title, 'lead': item.lead, 'text': item.text, 'publication_start': publication_start, 'publication_end': publication_end, 'created': item.created.isoformat(), 'modified': get_modified_iso_format(item), }