Context manager to obtain a connection from the pool. Return the connection immediately if available, otherwise wait up to *timeout* or `self.timeout` seconds and throw `PoolTimeout` if a connection is not available in time. Upon context exit, return the connection
(self, timeout: float | None = None)
| 170 | |
| 171 | @contextmanager |
| 172 | def connection(self, timeout: float | None = None) -> Iterator[CT]: |
| 173 | """Context manager to obtain a connection from the pool. |
| 174 | |
| 175 | Return the connection immediately if available, otherwise wait up to |
| 176 | *timeout* or `self.timeout` seconds and throw `PoolTimeout` if a |
| 177 | connection is not available in time. |
| 178 | |
| 179 | Upon context exit, return the connection to the pool. Apply the normal |
| 180 | :ref:`connection context behaviour <with-connection>` (commit/rollback |
| 181 | the transaction in case of success/error). If the connection is no more |
| 182 | in working state, replace it with a new one. |
| 183 | """ |
| 184 | conn = self.getconn(timeout=timeout) |
| 185 | try: |
| 186 | t0 = monotonic() |
| 187 | with conn: |
| 188 | yield conn |
| 189 | finally: |
| 190 | self.putconn(conn) |
| 191 | t1 = monotonic() |
| 192 | self._stats[self._USAGE_MS] += int(1000.0 * (t1 - t0)) |
| 193 | |
| 194 | def getconn(self, timeout: float | None = None) -> CT: |
| 195 | """Obtain a connection from the pool. |