[Python] Firestore - Querying a collection based on current time

Discussão em 'Python' iniciado por Stack, Fevereiro 19, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to retrieve a list of events stored in a Firestore collection in Python. I want to retrieve only future events (but I also want to keep past events up to 2 hours).

    I also want to listen on the collection in case of changes on the future schedule.

    The problem I'm facing is that when I run my script and my on_snapshot, the time with which I compare the “end” fields of my events is equal to the time when I ran the script. The datetime doesn't update itself.

    MAX_EVENTS_SHOWN = 4

    def on_events(doc_snapshot, changes, read_time):
    global next_sessions_shown, next_sessions

    try:
    next_sessions_shown.clear()
    next_sessions.clear()

    # on init and on change, same for loop is used
    all_docs = list(doc_snapshot) + [change.document for change in changes]

    # init events on screen
    for index, doc in enumerate(all_docs):
    data = doc.to_dict()

    # only show 4 future events
    if index <= MAX_EVENTS_SHOWN - 1:
    next_sessions_shown.append(doc.id)


    next_sessions.append(doc.id)


    except Exception as error:
    print_now(f"Error in on_events function: {error}")


    if __name__ == '__main__':
    get_all_upcoming_events_fs_doc().on_snapshot(on_events)


    _FS_CRM_ROOT = 'v3'
    _FS_EVENTS = _FS_CRM_ROOT + '/events'

    def get_all_upcoming_events_fs_doc():
    utc_plus_1 = timezone(timedelta(hours=1))

    # convert to UTC+1 (current local here)
    now = datetime.utcnow().replace(tzinfo=timezone.utc).astimezone(utc_plus_1)

    # 2H hours ago from now
    two_hours_ago = now - timedelta(hours=2)

    return db.collection(_FS_EVENTS).order_by("end").where(filter=FieldFilter("end", ">=", two_hours_ago))



    I've already tried resetting the listener every minute with a thread, without success. I got an error message like: "Background thread did not exit".

    Thank you in advance.

    Continue reading...

Compartilhe esta Página