Yield `Notify` objects as soon as they are received from the database. :param timeout: maximum amount of time to wait for notifications. `!None` means no timeout. :param stop_after: stop after receiving this number of notifications. You might actuall
(
self, *, timeout: float | None = None, stop_after: int | None = None
)
| 363 | yield tx |
| 364 | |
| 365 | def notifies( |
| 366 | self, *, timeout: float | None = None, stop_after: int | None = None |
| 367 | ) -> Generator[Notify]: |
| 368 | """ |
| 369 | Yield `Notify` objects as soon as they are received from the database. |
| 370 | |
| 371 | :param timeout: maximum amount of time to wait for notifications. |
| 372 | `!None` means no timeout. |
| 373 | :param stop_after: stop after receiving this number of notifications. |
| 374 | You might actually receive more than this number if more than one |
| 375 | notifications arrives in the same packet. |
| 376 | """ |
| 377 | # Allow interrupting the wait with a signal by reducing a long timeout |
| 378 | # into shorter intervals. |
| 379 | if timeout is not None: |
| 380 | deadline = monotonic() + timeout |
| 381 | interval = min(timeout, _WAIT_INTERVAL) |
| 382 | else: |
| 383 | deadline = None |
| 384 | interval = _WAIT_INTERVAL |
| 385 | |
| 386 | nreceived = 0 |
| 387 | |
| 388 | if self._notify_handlers: |
| 389 | warnings.warn( |
| 390 | "using 'notifies()' together with notifies handlers on the same connection is not reliable. Please use only one of these methods", |
| 391 | RuntimeWarning, |
| 392 | ) |
| 393 | |
| 394 | with self.lock: |
| 395 | enc = self.pgconn._encoding |
| 396 | |
| 397 | # Remove the backlog deque for the duration of this critical |
| 398 | # section to avoid reporting notifies twice. |
| 399 | self._notifies_backlog, d = (None, self._notifies_backlog) |
| 400 | |
| 401 | try: |
| 402 | while True: |
| 403 | # if notifies were received when the generator was off, |
| 404 | # return them in a first batch. |
| 405 | if d: |
| 406 | while d: |
| 407 | yield d.popleft() |
| 408 | nreceived += 1 |
| 409 | else: |
| 410 | try: |
| 411 | pgns = self.wait(notifies(self.pgconn), interval=interval) |
| 412 | except e._NO_TRACEBACK as ex: |
| 413 | raise ex.with_traceback(None) |
| 414 | # Emit the notifications received. |
| 415 | for pgn in pgns: |
| 416 | yield Notify( |
| 417 | pgn.relname.decode(enc), |
| 418 | pgn.extra.decode(enc), |
| 419 | pgn.be_pid, |
| 420 | ) |
| 421 | nreceived += 1 |
| 422 |