Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1# orm/events.py 

2# Copyright (C) 2005-2020 the SQLAlchemy authors and contributors 

3# <see AUTHORS file> 

4# 

5# This module is part of SQLAlchemy and is released under 

6# the MIT License: http://www.opensource.org/licenses/mit-license.php 

7 

8"""ORM event interfaces. 

9 

10""" 

11import weakref 

12 

13from . import instrumentation 

14from . import interfaces 

15from . import mapperlib 

16from .attributes import QueryableAttribute 

17from .base import _mapper_or_none 

18from .query import Query 

19from .scoping import scoped_session 

20from .session import Session 

21from .session import sessionmaker 

22from .. import event 

23from .. import exc 

24from .. import util 

25from ..util.compat import inspect_getfullargspec 

26 

27 

28class InstrumentationEvents(event.Events): 

29 """Events related to class instrumentation events. 

30 

31 The listeners here support being established against 

32 any new style class, that is any object that is a subclass 

33 of 'type'. Events will then be fired off for events 

34 against that class. If the "propagate=True" flag is passed 

35 to event.listen(), the event will fire off for subclasses 

36 of that class as well. 

37 

38 The Python ``type`` builtin is also accepted as a target, 

39 which when used has the effect of events being emitted 

40 for all classes. 

41 

42 Note the "propagate" flag here is defaulted to ``True``, 

43 unlike the other class level events where it defaults 

44 to ``False``. This means that new subclasses will also 

45 be the subject of these events, when a listener 

46 is established on a superclass. 

47 

48 """ 

49 

50 _target_class_doc = "SomeBaseClass" 

51 _dispatch_target = instrumentation.InstrumentationFactory 

52 

53 @classmethod 

54 def _accept_with(cls, target): 

55 if isinstance(target, type): 

56 return _InstrumentationEventsHold(target) 

57 else: 

58 return None 

59 

60 @classmethod 

61 def _listen(cls, event_key, propagate=True, **kw): 

62 target, identifier, fn = ( 

63 event_key.dispatch_target, 

64 event_key.identifier, 

65 event_key._listen_fn, 

66 ) 

67 

68 def listen(target_cls, *arg): 

69 listen_cls = target() 

70 if propagate and issubclass(target_cls, listen_cls): 

71 return fn(target_cls, *arg) 

72 elif not propagate and target_cls is listen_cls: 

73 return fn(target_cls, *arg) 

74 

75 def remove(ref): 

76 key = event.registry._EventKey( 

77 None, 

78 identifier, 

79 listen, 

80 instrumentation._instrumentation_factory, 

81 ) 

82 getattr( 

83 instrumentation._instrumentation_factory.dispatch, identifier 

84 ).remove(key) 

85 

86 target = weakref.ref(target.class_, remove) 

87 

88 event_key.with_dispatch_target( 

89 instrumentation._instrumentation_factory 

90 ).with_wrapper(listen).base_listen(**kw) 

91 

92 @classmethod 

93 def _clear(cls): 

94 super(InstrumentationEvents, cls)._clear() 

95 instrumentation._instrumentation_factory.dispatch._clear() 

96 

97 def class_instrument(self, cls): 

98 """Called after the given class is instrumented. 

99 

100 To get at the :class:`.ClassManager`, use 

101 :func:`.manager_of_class`. 

102 

103 """ 

104 

105 def class_uninstrument(self, cls): 

106 """Called before the given class is uninstrumented. 

107 

108 To get at the :class:`.ClassManager`, use 

109 :func:`.manager_of_class`. 

110 

111 """ 

112 

113 def attribute_instrument(self, cls, key, inst): 

114 """Called when an attribute is instrumented.""" 

115 

116 

117class _InstrumentationEventsHold(object): 

118 """temporary marker object used to transfer from _accept_with() to 

119 _listen() on the InstrumentationEvents class. 

120 

121 """ 

122 

123 def __init__(self, class_): 

124 self.class_ = class_ 

125 

126 dispatch = event.dispatcher(InstrumentationEvents) 

127 

128 

129class InstanceEvents(event.Events): 

130 """Define events specific to object lifecycle. 

131 

132 e.g.:: 

133 

134 from sqlalchemy import event 

135 

136 def my_load_listener(target, context): 

137 print("on load!") 

138 

139 event.listen(SomeClass, 'load', my_load_listener) 

140 

141 Available targets include: 

142 

143 * mapped classes 

144 * unmapped superclasses of mapped or to-be-mapped classes 

145 (using the ``propagate=True`` flag) 

146 * :class:`_orm.Mapper` objects 

147 * the :class:`_orm.Mapper` class itself and the :func:`.mapper` 

148 function indicate listening for all mappers. 

149 

150 Instance events are closely related to mapper events, but 

151 are more specific to the instance and its instrumentation, 

152 rather than its system of persistence. 

153 

154 When using :class:`.InstanceEvents`, several modifiers are 

155 available to the :func:`.event.listen` function. 

156 

157 :param propagate=False: When True, the event listener should 

158 be applied to all inheriting classes as well as the 

159 class which is the target of this listener. 

160 :param raw=False: When True, the "target" argument passed 

161 to applicable event listener functions will be the 

162 instance's :class:`.InstanceState` management 

163 object, rather than the mapped instance itself. 

164 :param restore_load_context=False: Applies to the 

165 :meth:`.InstanceEvents.load` and :meth:`.InstanceEvents.refresh` 

166 events. Restores the loader context of the object when the event 

167 hook is complete, so that ongoing eager load operations continue 

168 to target the object appropriately. A warning is emitted if the 

169 object is moved to a new loader context from within one of these 

170 events if this flag is not set. 

171 

172 .. versionadded:: 1.3.14 

173 

174 

175 """ 

176 

177 _target_class_doc = "SomeClass" 

178 

179 _dispatch_target = instrumentation.ClassManager 

180 

181 @classmethod 

182 def _new_classmanager_instance(cls, class_, classmanager): 

183 _InstanceEventsHold.populate(class_, classmanager) 

184 

185 @classmethod 

186 @util.dependencies("sqlalchemy.orm") 

187 def _accept_with(cls, orm, target): 

188 if isinstance(target, instrumentation.ClassManager): 

189 return target 

190 elif isinstance(target, mapperlib.Mapper): 

191 return target.class_manager 

192 elif target is orm.mapper: 

193 return instrumentation.ClassManager 

194 elif isinstance(target, type): 

195 if issubclass(target, mapperlib.Mapper): 

196 return instrumentation.ClassManager 

197 else: 

198 manager = instrumentation.manager_of_class(target) 

199 if manager: 

200 return manager 

201 else: 

202 return _InstanceEventsHold(target) 

203 return None 

204 

205 @classmethod 

206 def _listen( 

207 cls, 

208 event_key, 

209 raw=False, 

210 propagate=False, 

211 restore_load_context=False, 

212 **kw 

213 ): 

214 target, fn = (event_key.dispatch_target, event_key._listen_fn) 

215 

216 if not raw or restore_load_context: 

217 

218 def wrap(state, *arg, **kw): 

219 if not raw: 

220 target = state.obj() 

221 else: 

222 target = state 

223 if restore_load_context: 

224 runid = state.runid 

225 try: 

226 return fn(target, *arg, **kw) 

227 finally: 

228 if restore_load_context: 

229 state.runid = runid 

230 

231 event_key = event_key.with_wrapper(wrap) 

232 

233 event_key.base_listen(propagate=propagate, **kw) 

234 

235 if propagate: 

236 for mgr in target.subclass_managers(True): 

237 event_key.with_dispatch_target(mgr).base_listen(propagate=True) 

238 

239 @classmethod 

240 def _clear(cls): 

241 super(InstanceEvents, cls)._clear() 

242 _InstanceEventsHold._clear() 

243 

244 def first_init(self, manager, cls): 

245 """Called when the first instance of a particular mapping is called. 

246 

247 This event is called when the ``__init__`` method of a class 

248 is called the first time for that particular class. The event 

249 invokes before ``__init__`` actually proceeds as well as before 

250 the :meth:`.InstanceEvents.init` event is invoked. 

251 

252 """ 

253 

254 def init(self, target, args, kwargs): 

255 """Receive an instance when its constructor is called. 

256 

257 This method is only called during a userland construction of 

258 an object, in conjunction with the object's constructor, e.g. 

259 its ``__init__`` method. It is not called when an object is 

260 loaded from the database; see the :meth:`.InstanceEvents.load` 

261 event in order to intercept a database load. 

262 

263 The event is called before the actual ``__init__`` constructor 

264 of the object is called. The ``kwargs`` dictionary may be 

265 modified in-place in order to affect what is passed to 

266 ``__init__``. 

267 

268 :param target: the mapped instance. If 

269 the event is configured with ``raw=True``, this will 

270 instead be the :class:`.InstanceState` state-management 

271 object associated with the instance. 

272 :param args: positional arguments passed to the ``__init__`` method. 

273 This is passed as a tuple and is currently immutable. 

274 :param kwargs: keyword arguments passed to the ``__init__`` method. 

275 This structure *can* be altered in place. 

276 

277 .. seealso:: 

278 

279 :meth:`.InstanceEvents.init_failure` 

280 

281 :meth:`.InstanceEvents.load` 

282 

283 """ 

284 

285 def init_failure(self, target, args, kwargs): 

286 """Receive an instance when its constructor has been called, 

287 and raised an exception. 

288 

289 This method is only called during a userland construction of 

290 an object, in conjunction with the object's constructor, e.g. 

291 its ``__init__`` method. It is not called when an object is loaded 

292 from the database. 

293 

294 The event is invoked after an exception raised by the ``__init__`` 

295 method is caught. After the event 

296 is invoked, the original exception is re-raised outwards, so that 

297 the construction of the object still raises an exception. The 

298 actual exception and stack trace raised should be present in 

299 ``sys.exc_info()``. 

300 

301 :param target: the mapped instance. If 

302 the event is configured with ``raw=True``, this will 

303 instead be the :class:`.InstanceState` state-management 

304 object associated with the instance. 

305 :param args: positional arguments that were passed to the ``__init__`` 

306 method. 

307 :param kwargs: keyword arguments that were passed to the ``__init__`` 

308 method. 

309 

310 .. seealso:: 

311 

312 :meth:`.InstanceEvents.init` 

313 

314 :meth:`.InstanceEvents.load` 

315 

316 """ 

317 

318 def load(self, target, context): 

319 """Receive an object instance after it has been created via 

320 ``__new__``, and after initial attribute population has 

321 occurred. 

322 

323 This typically occurs when the instance is created based on 

324 incoming result rows, and is only called once for that 

325 instance's lifetime. 

326 

327 .. warning:: 

328 

329 During a result-row load, this event is invoked when the 

330 first row received for this instance is processed. When using 

331 eager loading with collection-oriented attributes, the additional 

332 rows that are to be loaded / processed in order to load subsequent 

333 collection items have not occurred yet. This has the effect 

334 both that collections will not be fully loaded, as well as that 

335 if an operation occurs within this event handler that emits 

336 another database load operation for the object, the "loading 

337 context" for the object can change and interfere with the 

338 existing eager loaders still in progress. 

339 

340 Examples of what can cause the "loading context" to change within 

341 the event handler include, but are not necessarily limited to: 

342 

343 * accessing deferred attributes that weren't part of the row, 

344 will trigger an "undefer" operation and refresh the object 

345 

346 * accessing attributes on a joined-inheritance subclass that 

347 weren't part of the row, will trigger a refresh operation. 

348 

349 As of SQLAlchemy 1.3.14, a warning is emitted when this occurs. The 

350 :paramref:`.InstanceEvents.restore_load_context` option may be 

351 used on the event to prevent this warning; this will ensure that 

352 the existing loading context is maintained for the object after the 

353 event is called:: 

354 

355 @event.listens_for( 

356 SomeClass, "load", restore_load_context=True) 

357 def on_load(instance, context): 

358 instance.some_unloaded_attribute 

359 

360 .. versionchanged:: 1.3.14 Added 

361 :paramref:`.InstanceEvents.restore_load_context` 

362 and :paramref:`.SessionEvents.restore_load_context` flags which 

363 apply to "on load" events, which will ensure that the loading 

364 context for an object is restored when the event hook is 

365 complete; a warning is emitted if the load context of the object 

366 changes without this flag being set. 

367 

368 

369 The :meth:`.InstanceEvents.load` event is also available in a 

370 class-method decorator format called :func:`_orm.reconstructor`. 

371 

372 :param target: the mapped instance. If 

373 the event is configured with ``raw=True``, this will 

374 instead be the :class:`.InstanceState` state-management 

375 object associated with the instance. 

376 :param context: the :class:`.QueryContext` corresponding to the 

377 current :class:`_query.Query` in progress. This argument may be 

378 ``None`` if the load does not correspond to a :class:`_query.Query`, 

379 such as during :meth:`.Session.merge`. 

380 

381 .. seealso:: 

382 

383 :meth:`.InstanceEvents.init` 

384 

385 :meth:`.InstanceEvents.refresh` 

386 

387 :meth:`.SessionEvents.loaded_as_persistent` 

388 

389 :ref:`mapping_constructors` 

390 

391 """ 

392 

393 def refresh(self, target, context, attrs): 

394 """Receive an object instance after one or more attributes have 

395 been refreshed from a query. 

396 

397 Contrast this to the :meth:`.InstanceEvents.load` method, which 

398 is invoked when the object is first loaded from a query. 

399 

400 .. note:: This event is invoked within the loader process before 

401 eager loaders may have been completed, and the object's state may 

402 not be complete. Additionally, invoking row-level refresh 

403 operations on the object will place the object into a new loader 

404 context, interfering with the existing load context. See the note 

405 on :meth:`.InstanceEvents.load` for background on making use of the 

406 :paramref:`.InstanceEvents.restore_load_context` parameter, in 

407 order to resolve this scenario. 

408 

409 :param target: the mapped instance. If 

410 the event is configured with ``raw=True``, this will 

411 instead be the :class:`.InstanceState` state-management 

412 object associated with the instance. 

413 :param context: the :class:`.QueryContext` corresponding to the 

414 current :class:`_query.Query` in progress. 

415 :param attrs: sequence of attribute names which 

416 were populated, or None if all column-mapped, non-deferred 

417 attributes were populated. 

418 

419 .. seealso:: 

420 

421 :meth:`.InstanceEvents.load` 

422 

423 """ 

424 

425 def refresh_flush(self, target, flush_context, attrs): 

426 """Receive an object instance after one or more attributes that 

427 contain a column-level default or onupdate handler have been refreshed 

428 during persistence of the object's state. 

429 

430 This event is the same as :meth:`.InstanceEvents.refresh` except 

431 it is invoked within the unit of work flush process, and includes 

432 only non-primary-key columns that have column level default or 

433 onupdate handlers, including Python callables as well as server side 

434 defaults and triggers which may be fetched via the RETURNING clause. 

435 

436 .. note:: 

437 

438 While the :meth:`.InstanceEvents.refresh_flush` event is triggered 

439 for an object that was INSERTed as well as for an object that was 

440 UPDATEd, the event is geared primarily towards the UPDATE process; 

441 it is mostly an internal artifact that INSERT actions can also 

442 trigger this event, and note that **primary key columns for an 

443 INSERTed row are explicitly omitted** from this event. In order to 

444 intercept the newly INSERTed state of an object, the 

445 :meth:`.SessionEvents.pending_to_persistent` and 

446 :meth:`.MapperEvents.after_insert` are better choices. 

447 

448 .. versionadded:: 1.0.5 

449 

450 :param target: the mapped instance. If 

451 the event is configured with ``raw=True``, this will 

452 instead be the :class:`.InstanceState` state-management 

453 object associated with the instance. 

454 :param flush_context: Internal :class:`.UOWTransaction` object 

455 which handles the details of the flush. 

456 :param attrs: sequence of attribute names which 

457 were populated. 

458 

459 .. seealso:: 

460 

461 :ref:`orm_server_defaults` 

462 

463 :ref:`metadata_defaults_toplevel` 

464 

465 """ 

466 

467 def expire(self, target, attrs): 

468 """Receive an object instance after its attributes or some subset 

469 have been expired. 

470 

471 'keys' is a list of attribute names. If None, the entire 

472 state was expired. 

473 

474 :param target: the mapped instance. If 

475 the event is configured with ``raw=True``, this will 

476 instead be the :class:`.InstanceState` state-management 

477 object associated with the instance. 

478 :param attrs: sequence of attribute 

479 names which were expired, or None if all attributes were 

480 expired. 

481 

482 """ 

483 

484 def pickle(self, target, state_dict): 

485 """Receive an object instance when its associated state is 

486 being pickled. 

487 

488 :param target: the mapped instance. If 

489 the event is configured with ``raw=True``, this will 

490 instead be the :class:`.InstanceState` state-management 

491 object associated with the instance. 

492 :param state_dict: the dictionary returned by 

493 :class:`.InstanceState.__getstate__`, containing the state 

494 to be pickled. 

495 

496 """ 

497 

498 def unpickle(self, target, state_dict): 

499 """Receive an object instance after its associated state has 

500 been unpickled. 

501 

502 :param target: the mapped instance. If 

503 the event is configured with ``raw=True``, this will 

504 instead be the :class:`.InstanceState` state-management 

505 object associated with the instance. 

506 :param state_dict: the dictionary sent to 

507 :class:`.InstanceState.__setstate__`, containing the state 

508 dictionary which was pickled. 

509 

510 """ 

511 

512 

513class _EventsHold(event.RefCollection): 

514 """Hold onto listeners against unmapped, uninstrumented classes. 

515 

516 Establish _listen() for that class' mapper/instrumentation when 

517 those objects are created for that class. 

518 

519 """ 

520 

521 def __init__(self, class_): 

522 self.class_ = class_ 

523 

524 @classmethod 

525 def _clear(cls): 

526 cls.all_holds.clear() 

527 

528 class HoldEvents(object): 

529 _dispatch_target = None 

530 

531 @classmethod 

532 def _listen( 

533 cls, event_key, raw=False, propagate=False, retval=False, **kw 

534 ): 

535 target = event_key.dispatch_target 

536 

537 if target.class_ in target.all_holds: 

538 collection = target.all_holds[target.class_] 

539 else: 

540 collection = target.all_holds[target.class_] = {} 

541 

542 event.registry._stored_in_collection(event_key, target) 

543 collection[event_key._key] = (event_key, raw, propagate, retval) 

544 

545 if propagate: 

546 stack = list(target.class_.__subclasses__()) 

547 while stack: 

548 subclass = stack.pop(0) 

549 stack.extend(subclass.__subclasses__()) 

550 subject = target.resolve(subclass) 

551 if subject is not None: 

552 # we are already going through __subclasses__() 

553 # so leave generic propagate flag False 

554 event_key.with_dispatch_target(subject).listen( 

555 raw=raw, propagate=False, retval=retval, **kw 

556 ) 

557 

558 def remove(self, event_key): 

559 target = event_key.dispatch_target 

560 

561 if isinstance(target, _EventsHold): 

562 collection = target.all_holds[target.class_] 

563 del collection[event_key._key] 

564 

565 @classmethod 

566 def populate(cls, class_, subject): 

567 for subclass in class_.__mro__: 

568 if subclass in cls.all_holds: 

569 collection = cls.all_holds[subclass] 

570 for event_key, raw, propagate, retval in collection.values(): 

571 if propagate or subclass is class_: 

572 # since we can't be sure in what order different 

573 # classes in a hierarchy are triggered with 

574 # populate(), we rely upon _EventsHold for all event 

575 # assignment, instead of using the generic propagate 

576 # flag. 

577 event_key.with_dispatch_target(subject).listen( 

578 raw=raw, propagate=False, retval=retval 

579 ) 

580 

581 

582class _InstanceEventsHold(_EventsHold): 

583 all_holds = weakref.WeakKeyDictionary() 

584 

585 def resolve(self, class_): 

586 return instrumentation.manager_of_class(class_) 

587 

588 class HoldInstanceEvents(_EventsHold.HoldEvents, InstanceEvents): 

589 pass 

590 

591 dispatch = event.dispatcher(HoldInstanceEvents) 

592 

593 

594class MapperEvents(event.Events): 

595 """Define events specific to mappings. 

596 

597 e.g.:: 

598 

599 from sqlalchemy import event 

600 

601 def my_before_insert_listener(mapper, connection, target): 

602 # execute a stored procedure upon INSERT, 

603 # apply the value to the row to be inserted 

604 target.calculated_value = connection.scalar( 

605 "select my_special_function(%d)" 

606 % target.special_number) 

607 

608 # associate the listener function with SomeClass, 

609 # to execute during the "before_insert" hook 

610 event.listen( 

611 SomeClass, 'before_insert', my_before_insert_listener) 

612 

613 Available targets include: 

614 

615 * mapped classes 

616 * unmapped superclasses of mapped or to-be-mapped classes 

617 (using the ``propagate=True`` flag) 

618 * :class:`_orm.Mapper` objects 

619 * the :class:`_orm.Mapper` class itself and the :func:`.mapper` 

620 function indicate listening for all mappers. 

621 

622 Mapper events provide hooks into critical sections of the 

623 mapper, including those related to object instrumentation, 

624 object loading, and object persistence. In particular, the 

625 persistence methods :meth:`~.MapperEvents.before_insert`, 

626 and :meth:`~.MapperEvents.before_update` are popular 

627 places to augment the state being persisted - however, these 

628 methods operate with several significant restrictions. The 

629 user is encouraged to evaluate the 

630 :meth:`.SessionEvents.before_flush` and 

631 :meth:`.SessionEvents.after_flush` methods as more 

632 flexible and user-friendly hooks in which to apply 

633 additional database state during a flush. 

634 

635 When using :class:`.MapperEvents`, several modifiers are 

636 available to the :func:`.event.listen` function. 

637 

638 :param propagate=False: When True, the event listener should 

639 be applied to all inheriting mappers and/or the mappers of 

640 inheriting classes, as well as any 

641 mapper which is the target of this listener. 

642 :param raw=False: When True, the "target" argument passed 

643 to applicable event listener functions will be the 

644 instance's :class:`.InstanceState` management 

645 object, rather than the mapped instance itself. 

646 :param retval=False: when True, the user-defined event function 

647 must have a return value, the purpose of which is either to 

648 control subsequent event propagation, or to otherwise alter 

649 the operation in progress by the mapper. Possible return 

650 values are: 

651 

652 * ``sqlalchemy.orm.interfaces.EXT_CONTINUE`` - continue event 

653 processing normally. 

654 * ``sqlalchemy.orm.interfaces.EXT_STOP`` - cancel all subsequent 

655 event handlers in the chain. 

656 * other values - the return value specified by specific listeners. 

657 

658 """ 

659 

660 _target_class_doc = "SomeClass" 

661 _dispatch_target = mapperlib.Mapper 

662 

663 @classmethod 

664 def _new_mapper_instance(cls, class_, mapper): 

665 _MapperEventsHold.populate(class_, mapper) 

666 

667 @classmethod 

668 @util.dependencies("sqlalchemy.orm") 

669 def _accept_with(cls, orm, target): 

670 if target is orm.mapper: 

671 return mapperlib.Mapper 

672 elif isinstance(target, type): 

673 if issubclass(target, mapperlib.Mapper): 

674 return target 

675 else: 

676 mapper = _mapper_or_none(target) 

677 if mapper is not None: 

678 return mapper 

679 else: 

680 return _MapperEventsHold(target) 

681 else: 

682 return target 

683 

684 @classmethod 

685 def _listen( 

686 cls, event_key, raw=False, retval=False, propagate=False, **kw 

687 ): 

688 target, identifier, fn = ( 

689 event_key.dispatch_target, 

690 event_key.identifier, 

691 event_key._listen_fn, 

692 ) 

693 

694 if ( 

695 identifier in ("before_configured", "after_configured") 

696 and target is not mapperlib.Mapper 

697 ): 

698 util.warn( 

699 "'before_configured' and 'after_configured' ORM events " 

700 "only invoke with the mapper() function or Mapper class " 

701 "as the target." 

702 ) 

703 

704 if not raw or not retval: 

705 if not raw: 

706 meth = getattr(cls, identifier) 

707 try: 

708 target_index = ( 

709 inspect_getfullargspec(meth)[0].index("target") - 1 

710 ) 

711 except ValueError: 

712 target_index = None 

713 

714 def wrap(*arg, **kw): 

715 if not raw and target_index is not None: 

716 arg = list(arg) 

717 arg[target_index] = arg[target_index].obj() 

718 if not retval: 

719 fn(*arg, **kw) 

720 return interfaces.EXT_CONTINUE 

721 else: 

722 return fn(*arg, **kw) 

723 

724 event_key = event_key.with_wrapper(wrap) 

725 

726 if propagate: 

727 for mapper in target.self_and_descendants: 

728 event_key.with_dispatch_target(mapper).base_listen( 

729 propagate=True, **kw 

730 ) 

731 else: 

732 event_key.base_listen(**kw) 

733 

734 @classmethod 

735 def _clear(cls): 

736 super(MapperEvents, cls)._clear() 

737 _MapperEventsHold._clear() 

738 

739 def instrument_class(self, mapper, class_): 

740 r"""Receive a class when the mapper is first constructed, 

741 before instrumentation is applied to the mapped class. 

742 

743 This event is the earliest phase of mapper construction. 

744 Most attributes of the mapper are not yet initialized. 

745 

746 This listener can either be applied to the :class:`_orm.Mapper` 

747 class overall, or to any un-mapped class which serves as a base 

748 for classes that will be mapped (using the ``propagate=True`` flag):: 

749 

750 Base = declarative_base() 

751 

752 @event.listens_for(Base, "instrument_class", propagate=True) 

753 def on_new_class(mapper, cls_): 

754 " ... " 

755 

756 :param mapper: the :class:`_orm.Mapper` which is the target 

757 of this event. 

758 :param class\_: the mapped class. 

759 

760 """ 

761 

762 def before_mapper_configured(self, mapper, class_): 

763 """Called right before a specific mapper is to be configured. 

764 

765 This event is intended to allow a specific mapper to be skipped during 

766 the configure step, by returning the :attr:`.orm.interfaces.EXT_SKIP` 

767 symbol which indicates to the :func:`.configure_mappers` call that this 

768 particular mapper (or hierarchy of mappers, if ``propagate=True`` is 

769 used) should be skipped in the current configuration run. When one or 

770 more mappers are skipped, the he "new mappers" flag will remain set, 

771 meaning the :func:`.configure_mappers` function will continue to be 

772 called when mappers are used, to continue to try to configure all 

773 available mappers. 

774 

775 In comparison to the other configure-level events, 

776 :meth:`.MapperEvents.before_configured`, 

777 :meth:`.MapperEvents.after_configured`, and 

778 :meth:`.MapperEvents.mapper_configured`, the 

779 :meth;`.MapperEvents.before_mapper_configured` event provides for a 

780 meaningful return value when it is registered with the ``retval=True`` 

781 parameter. 

782 

783 .. versionadded:: 1.3 

784 

785 e.g.:: 

786 

787 from sqlalchemy.orm import EXT_SKIP 

788 

789 Base = declarative_base() 

790 

791 DontConfigureBase = declarative_base() 

792 

793 @event.listens_for( 

794 DontConfigureBase, 

795 "before_mapper_configured", retval=True, propagate=True) 

796 def dont_configure(mapper, cls): 

797 return EXT_SKIP 

798 

799 

800 .. seealso:: 

801 

802 :meth:`.MapperEvents.before_configured` 

803 

804 :meth:`.MapperEvents.after_configured` 

805 

806 :meth:`.MapperEvents.mapper_configured` 

807 

808 """ 

809 

810 def mapper_configured(self, mapper, class_): 

811 r"""Called when a specific mapper has completed its own configuration 

812 within the scope of the :func:`.configure_mappers` call. 

813 

814 The :meth:`.MapperEvents.mapper_configured` event is invoked 

815 for each mapper that is encountered when the 

816 :func:`_orm.configure_mappers` function proceeds through the current 

817 list of not-yet-configured mappers. 

818 :func:`_orm.configure_mappers` is typically invoked 

819 automatically as mappings are first used, as well as each time 

820 new mappers have been made available and new mapper use is 

821 detected. 

822 

823 When the event is called, the mapper should be in its final 

824 state, but **not including backrefs** that may be invoked from 

825 other mappers; they might still be pending within the 

826 configuration operation. Bidirectional relationships that 

827 are instead configured via the 

828 :paramref:`.orm.relationship.back_populates` argument 

829 *will* be fully available, since this style of relationship does not 

830 rely upon other possibly-not-configured mappers to know that they 

831 exist. 

832 

833 For an event that is guaranteed to have **all** mappers ready 

834 to go including backrefs that are defined only on other 

835 mappings, use the :meth:`.MapperEvents.after_configured` 

836 event; this event invokes only after all known mappings have been 

837 fully configured. 

838 

839 The :meth:`.MapperEvents.mapper_configured` event, unlike 

840 :meth:`.MapperEvents.before_configured` or 

841 :meth:`.MapperEvents.after_configured`, 

842 is called for each mapper/class individually, and the mapper is 

843 passed to the event itself. It also is called exactly once for 

844 a particular mapper. The event is therefore useful for 

845 configurational steps that benefit from being invoked just once 

846 on a specific mapper basis, which don't require that "backref" 

847 configurations are necessarily ready yet. 

848 

849 :param mapper: the :class:`_orm.Mapper` which is the target 

850 of this event. 

851 :param class\_: the mapped class. 

852 

853 .. seealso:: 

854 

855 :meth:`.MapperEvents.before_configured` 

856 

857 :meth:`.MapperEvents.after_configured` 

858 

859 :meth:`.MapperEvents.before_mapper_configured` 

860 

861 """ 

862 # TODO: need coverage for this event 

863 

864 def before_configured(self): 

865 """Called before a series of mappers have been configured. 

866 

867 The :meth:`.MapperEvents.before_configured` event is invoked 

868 each time the :func:`_orm.configure_mappers` function is 

869 invoked, before the function has done any of its work. 

870 :func:`_orm.configure_mappers` is typically invoked 

871 automatically as mappings are first used, as well as each time 

872 new mappers have been made available and new mapper use is 

873 detected. 

874 

875 This event can **only** be applied to the :class:`_orm.Mapper` class 

876 or :func:`.mapper` function, and not to individual mappings or 

877 mapped classes. It is only invoked for all mappings as a whole:: 

878 

879 from sqlalchemy.orm import mapper 

880 

881 @event.listens_for(mapper, "before_configured") 

882 def go(): 

883 # ... 

884 

885 Contrast this event to :meth:`.MapperEvents.after_configured`, 

886 which is invoked after the series of mappers has been configured, 

887 as well as :meth:`.MapperEvents.before_mapper_configured` 

888 and :meth:`.MapperEvents.mapper_configured`, which are both invoked 

889 on a per-mapper basis. 

890 

891 Theoretically this event is called once per 

892 application, but is actually called any time new mappers 

893 are to be affected by a :func:`_orm.configure_mappers` 

894 call. If new mappings are constructed after existing ones have 

895 already been used, this event will likely be called again. To ensure 

896 that a particular event is only called once and no further, the 

897 ``once=True`` argument (new in 0.9.4) can be applied:: 

898 

899 from sqlalchemy.orm import mapper 

900 

901 @event.listens_for(mapper, "before_configured", once=True) 

902 def go(): 

903 # ... 

904 

905 

906 .. versionadded:: 0.9.3 

907 

908 

909 .. seealso:: 

910 

911 :meth:`.MapperEvents.before_mapper_configured` 

912 

913 :meth:`.MapperEvents.mapper_configured` 

914 

915 :meth:`.MapperEvents.after_configured` 

916 

917 """ 

918 

919 def after_configured(self): 

920 """Called after a series of mappers have been configured. 

921 

922 The :meth:`.MapperEvents.after_configured` event is invoked 

923 each time the :func:`_orm.configure_mappers` function is 

924 invoked, after the function has completed its work. 

925 :func:`_orm.configure_mappers` is typically invoked 

926 automatically as mappings are first used, as well as each time 

927 new mappers have been made available and new mapper use is 

928 detected. 

929 

930 Contrast this event to the :meth:`.MapperEvents.mapper_configured` 

931 event, which is called on a per-mapper basis while the configuration 

932 operation proceeds; unlike that event, when this event is invoked, 

933 all cross-configurations (e.g. backrefs) will also have been made 

934 available for any mappers that were pending. 

935 Also contrast to :meth:`.MapperEvents.before_configured`, 

936 which is invoked before the series of mappers has been configured. 

937 

938 This event can **only** be applied to the :class:`_orm.Mapper` class 

939 or :func:`.mapper` function, and not to individual mappings or 

940 mapped classes. It is only invoked for all mappings as a whole:: 

941 

942 from sqlalchemy.orm import mapper 

943 

944 @event.listens_for(mapper, "after_configured") 

945 def go(): 

946 # ... 

947 

948 Theoretically this event is called once per 

949 application, but is actually called any time new mappers 

950 have been affected by a :func:`_orm.configure_mappers` 

951 call. If new mappings are constructed after existing ones have 

952 already been used, this event will likely be called again. To ensure 

953 that a particular event is only called once and no further, the 

954 ``once=True`` argument (new in 0.9.4) can be applied:: 

955 

956 from sqlalchemy.orm import mapper 

957 

958 @event.listens_for(mapper, "after_configured", once=True) 

959 def go(): 

960 # ... 

961 

962 .. seealso:: 

963 

964 :meth:`.MapperEvents.before_mapper_configured` 

965 

966 :meth:`.MapperEvents.mapper_configured` 

967 

968 :meth:`.MapperEvents.before_configured` 

969 

970 """ 

971 

972 def before_insert(self, mapper, connection, target): 

973 """Receive an object instance before an INSERT statement 

974 is emitted corresponding to that instance. 

975 

976 This event is used to modify local, non-object related 

977 attributes on the instance before an INSERT occurs, as well 

978 as to emit additional SQL statements on the given 

979 connection. 

980 

981 The event is often called for a batch of objects of the 

982 same class before their INSERT statements are emitted at 

983 once in a later step. In the extremely rare case that 

984 this is not desirable, the :func:`.mapper` can be 

985 configured with ``batch=False``, which will cause 

986 batches of instances to be broken up into individual 

987 (and more poorly performing) event->persist->event 

988 steps. 

989 

990 .. warning:: 

991 

992 Mapper-level flush events only allow **very limited operations**, 

993 on attributes local to the row being operated upon only, 

994 as well as allowing any SQL to be emitted on the given 

995 :class:`_engine.Connection`. **Please read fully** the notes 

996 at :ref:`session_persistence_mapper` for guidelines on using 

997 these methods; generally, the :meth:`.SessionEvents.before_flush` 

998 method should be preferred for general on-flush changes. 

999 

1000 :param mapper: the :class:`_orm.Mapper` which is the target 

1001 of this event. 

1002 :param connection: the :class:`_engine.Connection` being used to 

1003 emit INSERT statements for this instance. This 

1004 provides a handle into the current transaction on the 

1005 target database specific to this instance. 

1006 :param target: the mapped instance being persisted. If 

1007 the event is configured with ``raw=True``, this will 

1008 instead be the :class:`.InstanceState` state-management 

1009 object associated with the instance. 

1010 :return: No return value is supported by this event. 

1011 

1012 .. seealso:: 

1013 

1014 :ref:`session_persistence_events` 

1015 

1016 """ 

1017 

1018 def after_insert(self, mapper, connection, target): 

1019 """Receive an object instance after an INSERT statement 

1020 is emitted corresponding to that instance. 

1021 

1022 This event is used to modify in-Python-only 

1023 state on the instance after an INSERT occurs, as well 

1024 as to emit additional SQL statements on the given 

1025 connection. 

1026 

1027 The event is often called for a batch of objects of the 

1028 same class after their INSERT statements have been 

1029 emitted at once in a previous step. In the extremely 

1030 rare case that this is not desirable, the 

1031 :func:`.mapper` can be configured with ``batch=False``, 

1032 which will cause batches of instances to be broken up 

1033 into individual (and more poorly performing) 

1034 event->persist->event steps. 

1035 

1036 .. warning:: 

1037 

1038 Mapper-level flush events only allow **very limited operations**, 

1039 on attributes local to the row being operated upon only, 

1040 as well as allowing any SQL to be emitted on the given 

1041 :class:`_engine.Connection`. **Please read fully** the notes 

1042 at :ref:`session_persistence_mapper` for guidelines on using 

1043 these methods; generally, the :meth:`.SessionEvents.before_flush` 

1044 method should be preferred for general on-flush changes. 

1045 

1046 :param mapper: the :class:`_orm.Mapper` which is the target 

1047 of this event. 

1048 :param connection: the :class:`_engine.Connection` being used to 

1049 emit INSERT statements for this instance. This 

1050 provides a handle into the current transaction on the 

1051 target database specific to this instance. 

1052 :param target: the mapped instance being persisted. If 

1053 the event is configured with ``raw=True``, this will 

1054 instead be the :class:`.InstanceState` state-management 

1055 object associated with the instance. 

1056 :return: No return value is supported by this event. 

1057 

1058 .. seealso:: 

1059 

1060 :ref:`session_persistence_events` 

1061 

1062 """ 

1063 

1064 def before_update(self, mapper, connection, target): 

1065 """Receive an object instance before an UPDATE statement 

1066 is emitted corresponding to that instance. 

1067 

1068 This event is used to modify local, non-object related 

1069 attributes on the instance before an UPDATE occurs, as well 

1070 as to emit additional SQL statements on the given 

1071 connection. 

1072 

1073 This method is called for all instances that are 

1074 marked as "dirty", *even those which have no net changes 

1075 to their column-based attributes*. An object is marked 

1076 as dirty when any of its column-based attributes have a 

1077 "set attribute" operation called or when any of its 

1078 collections are modified. If, at update time, no 

1079 column-based attributes have any net changes, no UPDATE 

1080 statement will be issued. This means that an instance 

1081 being sent to :meth:`~.MapperEvents.before_update` is 

1082 *not* a guarantee that an UPDATE statement will be 

1083 issued, although you can affect the outcome here by 

1084 modifying attributes so that a net change in value does 

1085 exist. 

1086 

1087 To detect if the column-based attributes on the object have net 

1088 changes, and will therefore generate an UPDATE statement, use 

1089 ``object_session(instance).is_modified(instance, 

1090 include_collections=False)``. 

1091 

1092 The event is often called for a batch of objects of the 

1093 same class before their UPDATE statements are emitted at 

1094 once in a later step. In the extremely rare case that 

1095 this is not desirable, the :func:`.mapper` can be 

1096 configured with ``batch=False``, which will cause 

1097 batches of instances to be broken up into individual 

1098 (and more poorly performing) event->persist->event 

1099 steps. 

1100 

1101 .. warning:: 

1102 

1103 Mapper-level flush events only allow **very limited operations**, 

1104 on attributes local to the row being operated upon only, 

1105 as well as allowing any SQL to be emitted on the given 

1106 :class:`_engine.Connection`. **Please read fully** the notes 

1107 at :ref:`session_persistence_mapper` for guidelines on using 

1108 these methods; generally, the :meth:`.SessionEvents.before_flush` 

1109 method should be preferred for general on-flush changes. 

1110 

1111 :param mapper: the :class:`_orm.Mapper` which is the target 

1112 of this event. 

1113 :param connection: the :class:`_engine.Connection` being used to 

1114 emit UPDATE statements for this instance. This 

1115 provides a handle into the current transaction on the 

1116 target database specific to this instance. 

1117 :param target: the mapped instance being persisted. If 

1118 the event is configured with ``raw=True``, this will 

1119 instead be the :class:`.InstanceState` state-management 

1120 object associated with the instance. 

1121 :return: No return value is supported by this event. 

1122 

1123 .. seealso:: 

1124 

1125 :ref:`session_persistence_events` 

1126 

1127 """ 

1128 

1129 def after_update(self, mapper, connection, target): 

1130 """Receive an object instance after an UPDATE statement 

1131 is emitted corresponding to that instance. 

1132 

1133 This event is used to modify in-Python-only 

1134 state on the instance after an UPDATE occurs, as well 

1135 as to emit additional SQL statements on the given 

1136 connection. 

1137 

1138 This method is called for all instances that are 

1139 marked as "dirty", *even those which have no net changes 

1140 to their column-based attributes*, and for which 

1141 no UPDATE statement has proceeded. An object is marked 

1142 as dirty when any of its column-based attributes have a 

1143 "set attribute" operation called or when any of its 

1144 collections are modified. If, at update time, no 

1145 column-based attributes have any net changes, no UPDATE 

1146 statement will be issued. This means that an instance 

1147 being sent to :meth:`~.MapperEvents.after_update` is 

1148 *not* a guarantee that an UPDATE statement has been 

1149 issued. 

1150 

1151 To detect if the column-based attributes on the object have net 

1152 changes, and therefore resulted in an UPDATE statement, use 

1153 ``object_session(instance).is_modified(instance, 

1154 include_collections=False)``. 

1155 

1156 The event is often called for a batch of objects of the 

1157 same class after their UPDATE statements have been emitted at 

1158 once in a previous step. In the extremely rare case that 

1159 this is not desirable, the :func:`.mapper` can be 

1160 configured with ``batch=False``, which will cause 

1161 batches of instances to be broken up into individual 

1162 (and more poorly performing) event->persist->event 

1163 steps. 

1164 

1165 .. warning:: 

1166 

1167 Mapper-level flush events only allow **very limited operations**, 

1168 on attributes local to the row being operated upon only, 

1169 as well as allowing any SQL to be emitted on the given 

1170 :class:`_engine.Connection`. **Please read fully** the notes 

1171 at :ref:`session_persistence_mapper` for guidelines on using 

1172 these methods; generally, the :meth:`.SessionEvents.before_flush` 

1173 method should be preferred for general on-flush changes. 

1174 

1175 :param mapper: the :class:`_orm.Mapper` which is the target 

1176 of this event. 

1177 :param connection: the :class:`_engine.Connection` being used to 

1178 emit UPDATE statements for this instance. This 

1179 provides a handle into the current transaction on the 

1180 target database specific to this instance. 

1181 :param target: the mapped instance being persisted. If 

1182 the event is configured with ``raw=True``, this will 

1183 instead be the :class:`.InstanceState` state-management 

1184 object associated with the instance. 

1185 :return: No return value is supported by this event. 

1186 

1187 .. seealso:: 

1188 

1189 :ref:`session_persistence_events` 

1190 

1191 """ 

1192 

1193 def before_delete(self, mapper, connection, target): 

1194 """Receive an object instance before a DELETE statement 

1195 is emitted corresponding to that instance. 

1196 

1197 This event is used to emit additional SQL statements on 

1198 the given connection as well as to perform application 

1199 specific bookkeeping related to a deletion event. 

1200 

1201 The event is often called for a batch of objects of the 

1202 same class before their DELETE statements are emitted at 

1203 once in a later step. 

1204 

1205 .. warning:: 

1206 

1207 Mapper-level flush events only allow **very limited operations**, 

1208 on attributes local to the row being operated upon only, 

1209 as well as allowing any SQL to be emitted on the given 

1210 :class:`_engine.Connection`. **Please read fully** the notes 

1211 at :ref:`session_persistence_mapper` for guidelines on using 

1212 these methods; generally, the :meth:`.SessionEvents.before_flush` 

1213 method should be preferred for general on-flush changes. 

1214 

1215 :param mapper: the :class:`_orm.Mapper` which is the target 

1216 of this event. 

1217 :param connection: the :class:`_engine.Connection` being used to 

1218 emit DELETE statements for this instance. This 

1219 provides a handle into the current transaction on the 

1220 target database specific to this instance. 

1221 :param target: the mapped instance being deleted. If 

1222 the event is configured with ``raw=True``, this will 

1223 instead be the :class:`.InstanceState` state-management 

1224 object associated with the instance. 

1225 :return: No return value is supported by this event. 

1226 

1227 .. seealso:: 

1228 

1229 :ref:`session_persistence_events` 

1230 

1231 """ 

1232 

1233 def after_delete(self, mapper, connection, target): 

1234 """Receive an object instance after a DELETE statement 

1235 has been emitted corresponding to that instance. 

1236 

1237 This event is used to emit additional SQL statements on 

1238 the given connection as well as to perform application 

1239 specific bookkeeping related to a deletion event. 

1240 

1241 The event is often called for a batch of objects of the 

1242 same class after their DELETE statements have been emitted at 

1243 once in a previous step. 

1244 

1245 .. warning:: 

1246 

1247 Mapper-level flush events only allow **very limited operations**, 

1248 on attributes local to the row being operated upon only, 

1249 as well as allowing any SQL to be emitted on the given 

1250 :class:`_engine.Connection`. **Please read fully** the notes 

1251 at :ref:`session_persistence_mapper` for guidelines on using 

1252 these methods; generally, the :meth:`.SessionEvents.before_flush` 

1253 method should be preferred for general on-flush changes. 

1254 

1255 :param mapper: the :class:`_orm.Mapper` which is the target 

1256 of this event. 

1257 :param connection: the :class:`_engine.Connection` being used to 

1258 emit DELETE statements for this instance. This 

1259 provides a handle into the current transaction on the 

1260 target database specific to this instance. 

1261 :param target: the mapped instance being deleted. If 

1262 the event is configured with ``raw=True``, this will 

1263 instead be the :class:`.InstanceState` state-management 

1264 object associated with the instance. 

1265 :return: No return value is supported by this event. 

1266 

1267 .. seealso:: 

1268 

1269 :ref:`session_persistence_events` 

1270 

1271 """ 

1272 

1273 

1274class _MapperEventsHold(_EventsHold): 

1275 all_holds = weakref.WeakKeyDictionary() 

1276 

1277 def resolve(self, class_): 

1278 return _mapper_or_none(class_) 

1279 

1280 class HoldMapperEvents(_EventsHold.HoldEvents, MapperEvents): 

1281 pass 

1282 

1283 dispatch = event.dispatcher(HoldMapperEvents) 

1284 

1285 

1286_sessionevents_lifecycle_event_names = set() 

1287 

1288 

1289class SessionEvents(event.Events): 

1290 """Define events specific to :class:`.Session` lifecycle. 

1291 

1292 e.g.:: 

1293 

1294 from sqlalchemy import event 

1295 from sqlalchemy.orm import sessionmaker 

1296 

1297 def my_before_commit(session): 

1298 print("before commit!") 

1299 

1300 Session = sessionmaker() 

1301 

1302 event.listen(Session, "before_commit", my_before_commit) 

1303 

1304 The :func:`~.event.listen` function will accept 

1305 :class:`.Session` objects as well as the return result 

1306 of :class:`~.sessionmaker()` and :class:`~.scoped_session()`. 

1307 

1308 Additionally, it accepts the :class:`.Session` class which 

1309 will apply listeners to all :class:`.Session` instances 

1310 globally. 

1311 

1312 :param raw=False: When True, the "target" argument passed 

1313 to applicable event listener functions that work on individual 

1314 objects will be the instance's :class:`.InstanceState` management 

1315 object, rather than the mapped instance itself. 

1316 

1317 .. versionadded:: 1.3.14 

1318 

1319 :param restore_load_context=False: Applies to the 

1320 :meth:`.SessionEvents.loaded_as_persistent` event. Restores the loader 

1321 context of the object when the event hook is complete, so that ongoing 

1322 eager load operations continue to target the object appropriately. A 

1323 warning is emitted if the object is moved to a new loader context from 

1324 within this event if this flag is not set. 

1325 

1326 .. versionadded:: 1.3.14 

1327 

1328 """ 

1329 

1330 _target_class_doc = "SomeSessionOrFactory" 

1331 

1332 _dispatch_target = Session 

1333 

1334 def _lifecycle_event(fn): 

1335 _sessionevents_lifecycle_event_names.add(fn.__name__) 

1336 return fn 

1337 

1338 @classmethod 

1339 def _accept_with(cls, target): 

1340 if isinstance(target, scoped_session): 

1341 

1342 target = target.session_factory 

1343 if not isinstance(target, sessionmaker) and ( 

1344 not isinstance(target, type) or not issubclass(target, Session) 

1345 ): 

1346 raise exc.ArgumentError( 

1347 "Session event listen on a scoped_session " 

1348 "requires that its creation callable " 

1349 "is associated with the Session class." 

1350 ) 

1351 

1352 if isinstance(target, sessionmaker): 

1353 return target.class_ 

1354 elif isinstance(target, type): 

1355 if issubclass(target, scoped_session): 

1356 return Session 

1357 elif issubclass(target, Session): 

1358 return target 

1359 elif isinstance(target, Session): 

1360 return target 

1361 else: 

1362 return None 

1363 

1364 @classmethod 

1365 def _listen(cls, event_key, raw=False, restore_load_context=False, **kw): 

1366 is_instance_event = ( 

1367 event_key.identifier in _sessionevents_lifecycle_event_names 

1368 ) 

1369 

1370 if is_instance_event: 

1371 if not raw or restore_load_context: 

1372 

1373 fn = event_key._listen_fn 

1374 

1375 def wrap(session, state, *arg, **kw): 

1376 if not raw: 

1377 target = state.obj() 

1378 if target is None: 

1379 # existing behavior is that if the object is 

1380 # garbage collected, no event is emitted 

1381 return 

1382 else: 

1383 target = state 

1384 if restore_load_context: 

1385 runid = state.runid 

1386 try: 

1387 return fn(session, target, *arg, **kw) 

1388 finally: 

1389 if restore_load_context: 

1390 state.runid = runid 

1391 

1392 event_key = event_key.with_wrapper(wrap) 

1393 

1394 event_key.base_listen(**kw) 

1395 

1396 def after_transaction_create(self, session, transaction): 

1397 """Execute when a new :class:`.SessionTransaction` is created. 

1398 

1399 This event differs from :meth:`~.SessionEvents.after_begin` 

1400 in that it occurs for each :class:`.SessionTransaction` 

1401 overall, as opposed to when transactions are begun 

1402 on individual database connections. It is also invoked 

1403 for nested transactions and subtransactions, and is always 

1404 matched by a corresponding 

1405 :meth:`~.SessionEvents.after_transaction_end` event 

1406 (assuming normal operation of the :class:`.Session`). 

1407 

1408 :param session: the target :class:`.Session`. 

1409 :param transaction: the target :class:`.SessionTransaction`. 

1410 

1411 To detect if this is the outermost 

1412 :class:`.SessionTransaction`, as opposed to a "subtransaction" or a 

1413 SAVEPOINT, test that the :attr:`.SessionTransaction.parent` attribute 

1414 is ``None``:: 

1415 

1416 @event.listens_for(session, "after_transaction_create") 

1417 def after_transaction_create(session, transaction): 

1418 if transaction.parent is None: 

1419 # work with top-level transaction 

1420 

1421 To detect if the :class:`.SessionTransaction` is a SAVEPOINT, use the 

1422 :attr:`.SessionTransaction.nested` attribute:: 

1423 

1424 @event.listens_for(session, "after_transaction_create") 

1425 def after_transaction_create(session, transaction): 

1426 if transaction.nested: 

1427 # work with SAVEPOINT transaction 

1428 

1429 

1430 .. seealso:: 

1431 

1432 :class:`.SessionTransaction` 

1433 

1434 :meth:`~.SessionEvents.after_transaction_end` 

1435 

1436 """ 

1437 

1438 def after_transaction_end(self, session, transaction): 

1439 """Execute when the span of a :class:`.SessionTransaction` ends. 

1440 

1441 This event differs from :meth:`~.SessionEvents.after_commit` 

1442 in that it corresponds to all :class:`.SessionTransaction` 

1443 objects in use, including those for nested transactions 

1444 and subtransactions, and is always matched by a corresponding 

1445 :meth:`~.SessionEvents.after_transaction_create` event. 

1446 

1447 :param session: the target :class:`.Session`. 

1448 :param transaction: the target :class:`.SessionTransaction`. 

1449 

1450 To detect if this is the outermost 

1451 :class:`.SessionTransaction`, as opposed to a "subtransaction" or a 

1452 SAVEPOINT, test that the :attr:`.SessionTransaction.parent` attribute 

1453 is ``None``:: 

1454 

1455 @event.listens_for(session, "after_transaction_create") 

1456 def after_transaction_end(session, transaction): 

1457 if transaction.parent is None: 

1458 # work with top-level transaction 

1459 

1460 To detect if the :class:`.SessionTransaction` is a SAVEPOINT, use the 

1461 :attr:`.SessionTransaction.nested` attribute:: 

1462 

1463 @event.listens_for(session, "after_transaction_create") 

1464 def after_transaction_end(session, transaction): 

1465 if transaction.nested: 

1466 # work with SAVEPOINT transaction 

1467 

1468 

1469 .. seealso:: 

1470 

1471 :class:`.SessionTransaction` 

1472 

1473 :meth:`~.SessionEvents.after_transaction_create` 

1474 

1475 """ 

1476 

1477 def before_commit(self, session): 

1478 """Execute before commit is called. 

1479 

1480 .. note:: 

1481 

1482 The :meth:`~.SessionEvents.before_commit` hook is *not* per-flush, 

1483 that is, the :class:`.Session` can emit SQL to the database 

1484 many times within the scope of a transaction. 

1485 For interception of these events, use the 

1486 :meth:`~.SessionEvents.before_flush`, 

1487 :meth:`~.SessionEvents.after_flush`, or 

1488 :meth:`~.SessionEvents.after_flush_postexec` 

1489 events. 

1490 

1491 :param session: The target :class:`.Session`. 

1492 

1493 .. seealso:: 

1494 

1495 :meth:`~.SessionEvents.after_commit` 

1496 

1497 :meth:`~.SessionEvents.after_begin` 

1498 

1499 :meth:`~.SessionEvents.after_transaction_create` 

1500 

1501 :meth:`~.SessionEvents.after_transaction_end` 

1502 

1503 """ 

1504 

1505 def after_commit(self, session): 

1506 """Execute after a commit has occurred. 

1507 

1508 .. note:: 

1509 

1510 The :meth:`~.SessionEvents.after_commit` hook is *not* per-flush, 

1511 that is, the :class:`.Session` can emit SQL to the database 

1512 many times within the scope of a transaction. 

1513 For interception of these events, use the 

1514 :meth:`~.SessionEvents.before_flush`, 

1515 :meth:`~.SessionEvents.after_flush`, or 

1516 :meth:`~.SessionEvents.after_flush_postexec` 

1517 events. 

1518 

1519 .. note:: 

1520 

1521 The :class:`.Session` is not in an active transaction 

1522 when the :meth:`~.SessionEvents.after_commit` event is invoked, 

1523 and therefore can not emit SQL. To emit SQL corresponding to 

1524 every transaction, use the :meth:`~.SessionEvents.before_commit` 

1525 event. 

1526 

1527 :param session: The target :class:`.Session`. 

1528 

1529 .. seealso:: 

1530 

1531 :meth:`~.SessionEvents.before_commit` 

1532 

1533 :meth:`~.SessionEvents.after_begin` 

1534 

1535 :meth:`~.SessionEvents.after_transaction_create` 

1536 

1537 :meth:`~.SessionEvents.after_transaction_end` 

1538 

1539 """ 

1540 

1541 def after_rollback(self, session): 

1542 """Execute after a real DBAPI rollback has occurred. 

1543 

1544 Note that this event only fires when the *actual* rollback against 

1545 the database occurs - it does *not* fire each time the 

1546 :meth:`.Session.rollback` method is called, if the underlying 

1547 DBAPI transaction has already been rolled back. In many 

1548 cases, the :class:`.Session` will not be in 

1549 an "active" state during this event, as the current 

1550 transaction is not valid. To acquire a :class:`.Session` 

1551 which is active after the outermost rollback has proceeded, 

1552 use the :meth:`.SessionEvents.after_soft_rollback` event, checking the 

1553 :attr:`.Session.is_active` flag. 

1554 

1555 :param session: The target :class:`.Session`. 

1556 

1557 """ 

1558 

1559 def after_soft_rollback(self, session, previous_transaction): 

1560 """Execute after any rollback has occurred, including "soft" 

1561 rollbacks that don't actually emit at the DBAPI level. 

1562 

1563 This corresponds to both nested and outer rollbacks, i.e. 

1564 the innermost rollback that calls the DBAPI's 

1565 rollback() method, as well as the enclosing rollback 

1566 calls that only pop themselves from the transaction stack. 

1567 

1568 The given :class:`.Session` can be used to invoke SQL and 

1569 :meth:`.Session.query` operations after an outermost rollback 

1570 by first checking the :attr:`.Session.is_active` flag:: 

1571 

1572 @event.listens_for(Session, "after_soft_rollback") 

1573 def do_something(session, previous_transaction): 

1574 if session.is_active: 

1575 session.execute("select * from some_table") 

1576 

1577 :param session: The target :class:`.Session`. 

1578 :param previous_transaction: The :class:`.SessionTransaction` 

1579 transactional marker object which was just closed. The current 

1580 :class:`.SessionTransaction` for the given :class:`.Session` is 

1581 available via the :attr:`.Session.transaction` attribute. 

1582 

1583 """ 

1584 

1585 def before_flush(self, session, flush_context, instances): 

1586 """Execute before flush process has started. 

1587 

1588 :param session: The target :class:`.Session`. 

1589 :param flush_context: Internal :class:`.UOWTransaction` object 

1590 which handles the details of the flush. 

1591 :param instances: Usually ``None``, this is the collection of 

1592 objects which can be passed to the :meth:`.Session.flush` method 

1593 (note this usage is deprecated). 

1594 

1595 .. seealso:: 

1596 

1597 :meth:`~.SessionEvents.after_flush` 

1598 

1599 :meth:`~.SessionEvents.after_flush_postexec` 

1600 

1601 :ref:`session_persistence_events` 

1602 

1603 """ 

1604 

1605 def after_flush(self, session, flush_context): 

1606 """Execute after flush has completed, but before commit has been 

1607 called. 

1608 

1609 Note that the session's state is still in pre-flush, i.e. 'new', 

1610 'dirty', and 'deleted' lists still show pre-flush state as well 

1611 as the history settings on instance attributes. 

1612 

1613 .. warning:: This event runs after the :class:`.Session` has emitted 

1614 SQL to modify the database, but **before** it has altered its 

1615 internal state to reflect those changes, including that newly 

1616 inserted objects are placed into the identity map. ORM operations 

1617 emitted within this event such as loads of related items 

1618 may produce new identity map entries that will immediately 

1619 be replaced, sometimes causing confusing results. SQLAlchemy will 

1620 emit a warning for this condition as of version 1.3.9. 

1621 

1622 :param session: The target :class:`.Session`. 

1623 :param flush_context: Internal :class:`.UOWTransaction` object 

1624 which handles the details of the flush. 

1625 

1626 .. seealso:: 

1627 

1628 :meth:`~.SessionEvents.before_flush` 

1629 

1630 :meth:`~.SessionEvents.after_flush_postexec` 

1631 

1632 :ref:`session_persistence_events` 

1633 

1634 """ 

1635 

1636 def after_flush_postexec(self, session, flush_context): 

1637 """Execute after flush has completed, and after the post-exec 

1638 state occurs. 

1639 

1640 This will be when the 'new', 'dirty', and 'deleted' lists are in 

1641 their final state. An actual commit() may or may not have 

1642 occurred, depending on whether or not the flush started its own 

1643 transaction or participated in a larger transaction. 

1644 

1645 :param session: The target :class:`.Session`. 

1646 :param flush_context: Internal :class:`.UOWTransaction` object 

1647 which handles the details of the flush. 

1648 

1649 

1650 .. seealso:: 

1651 

1652 :meth:`~.SessionEvents.before_flush` 

1653 

1654 :meth:`~.SessionEvents.after_flush` 

1655 

1656 :ref:`session_persistence_events` 

1657 

1658 """ 

1659 

1660 def after_begin(self, session, transaction, connection): 

1661 """Execute after a transaction is begun on a connection 

1662 

1663 :param session: The target :class:`.Session`. 

1664 :param transaction: The :class:`.SessionTransaction`. 

1665 :param connection: The :class:`_engine.Connection` object 

1666 which will be used for SQL statements. 

1667 

1668 .. seealso:: 

1669 

1670 :meth:`~.SessionEvents.before_commit` 

1671 

1672 :meth:`~.SessionEvents.after_commit` 

1673 

1674 :meth:`~.SessionEvents.after_transaction_create` 

1675 

1676 :meth:`~.SessionEvents.after_transaction_end` 

1677 

1678 """ 

1679 

1680 @_lifecycle_event 

1681 def before_attach(self, session, instance): 

1682 """Execute before an instance is attached to a session. 

1683 

1684 This is called before an add, delete or merge causes 

1685 the object to be part of the session. 

1686 

1687 .. seealso:: 

1688 

1689 :meth:`~.SessionEvents.after_attach` 

1690 

1691 :ref:`session_lifecycle_events` 

1692 

1693 """ 

1694 

1695 @_lifecycle_event 

1696 def after_attach(self, session, instance): 

1697 """Execute after an instance is attached to a session. 

1698 

1699 This is called after an add, delete or merge. 

1700 

1701 .. note:: 

1702 

1703 As of 0.8, this event fires off *after* the item 

1704 has been fully associated with the session, which is 

1705 different than previous releases. For event 

1706 handlers that require the object not yet 

1707 be part of session state (such as handlers which 

1708 may autoflush while the target object is not 

1709 yet complete) consider the 

1710 new :meth:`.before_attach` event. 

1711 

1712 .. seealso:: 

1713 

1714 :meth:`~.SessionEvents.before_attach` 

1715 

1716 :ref:`session_lifecycle_events` 

1717 

1718 """ 

1719 

1720 @event._legacy_signature( 

1721 "0.9", 

1722 ["session", "query", "query_context", "result"], 

1723 lambda update_context: ( 

1724 update_context.session, 

1725 update_context.query, 

1726 update_context.context, 

1727 update_context.result, 

1728 ), 

1729 ) 

1730 def after_bulk_update(self, update_context): 

1731 """Execute after a bulk update operation to the session. 

1732 

1733 This is called as a result of the :meth:`_query.Query.update` method. 

1734 

1735 :param update_context: an "update context" object which contains 

1736 details about the update, including these attributes: 

1737 

1738 * ``session`` - the :class:`.Session` involved 

1739 * ``query`` -the :class:`_query.Query` 

1740 object that this update operation 

1741 was called upon. 

1742 * ``values`` The "values" dictionary that was passed to 

1743 :meth:`_query.Query.update`. 

1744 * ``context`` The :class:`.QueryContext` object, corresponding 

1745 to the invocation of an ORM query. 

1746 * ``result`` the :class:`_engine.ResultProxy` 

1747 returned as a result of the 

1748 bulk UPDATE operation. 

1749 

1750 .. seealso:: 

1751 

1752 :meth:`.QueryEvents.before_compile_update` 

1753 

1754 :meth:`.SessionEvents.after_bulk_delete` 

1755 

1756 """ 

1757 

1758 @event._legacy_signature( 

1759 "0.9", 

1760 ["session", "query", "query_context", "result"], 

1761 lambda delete_context: ( 

1762 delete_context.session, 

1763 delete_context.query, 

1764 delete_context.context, 

1765 delete_context.result, 

1766 ), 

1767 ) 

1768 def after_bulk_delete(self, delete_context): 

1769 """Execute after a bulk delete operation to the session. 

1770 

1771 This is called as a result of the :meth:`_query.Query.delete` method. 

1772 

1773 :param delete_context: a "delete context" object which contains 

1774 details about the update, including these attributes: 

1775 

1776 * ``session`` - the :class:`.Session` involved 

1777 * ``query`` -the :class:`_query.Query` 

1778 object that this update operation 

1779 was called upon. 

1780 * ``context`` The :class:`.QueryContext` object, corresponding 

1781 to the invocation of an ORM query. 

1782 * ``result`` the :class:`_engine.ResultProxy` 

1783 returned as a result of the 

1784 bulk DELETE operation. 

1785 

1786 .. seealso:: 

1787 

1788 :meth:`.QueryEvents.before_compile_delete` 

1789 

1790 :meth:`.SessionEvents.after_bulk_update` 

1791 

1792 """ 

1793 

1794 @_lifecycle_event 

1795 def transient_to_pending(self, session, instance): 

1796 """Intercept the "transient to pending" transition for a specific object. 

1797 

1798 This event is a specialization of the 

1799 :meth:`.SessionEvents.after_attach` event which is only invoked 

1800 for this specific transition. It is invoked typically during the 

1801 :meth:`.Session.add` call. 

1802 

1803 :param session: target :class:`.Session` 

1804 

1805 :param instance: the ORM-mapped instance being operated upon. 

1806 

1807 .. versionadded:: 1.1 

1808 

1809 .. seealso:: 

1810 

1811 :ref:`session_lifecycle_events` 

1812 

1813 """ 

1814 

1815 @_lifecycle_event 

1816 def pending_to_transient(self, session, instance): 

1817 """Intercept the "pending to transient" transition for a specific object. 

1818 

1819 This less common transition occurs when an pending object that has 

1820 not been flushed is evicted from the session; this can occur 

1821 when the :meth:`.Session.rollback` method rolls back the transaction, 

1822 or when the :meth:`.Session.expunge` method is used. 

1823 

1824 :param session: target :class:`.Session` 

1825 

1826 :param instance: the ORM-mapped instance being operated upon. 

1827 

1828 .. versionadded:: 1.1 

1829 

1830 .. seealso:: 

1831 

1832 :ref:`session_lifecycle_events` 

1833 

1834 """ 

1835 

1836 @_lifecycle_event 

1837 def persistent_to_transient(self, session, instance): 

1838 """Intercept the "persistent to transient" transition for a specific object. 

1839 

1840 This less common transition occurs when an pending object that has 

1841 has been flushed is evicted from the session; this can occur 

1842 when the :meth:`.Session.rollback` method rolls back the transaction. 

1843 

1844 :param session: target :class:`.Session` 

1845 

1846 :param instance: the ORM-mapped instance being operated upon. 

1847 

1848 .. versionadded:: 1.1 

1849 

1850 .. seealso:: 

1851 

1852 :ref:`session_lifecycle_events` 

1853 

1854 """ 

1855 

1856 @_lifecycle_event 

1857 def pending_to_persistent(self, session, instance): 

1858 """Intercept the "pending to persistent"" transition for a specific object. 

1859 

1860 This event is invoked within the flush process, and is 

1861 similar to scanning the :attr:`.Session.new` collection within 

1862 the :meth:`.SessionEvents.after_flush` event. However, in this 

1863 case the object has already been moved to the persistent state 

1864 when the event is called. 

1865 

1866 :param session: target :class:`.Session` 

1867 

1868 :param instance: the ORM-mapped instance being operated upon. 

1869 

1870 .. versionadded:: 1.1 

1871 

1872 .. seealso:: 

1873 

1874 :ref:`session_lifecycle_events` 

1875 

1876 """ 

1877 

1878 @_lifecycle_event 

1879 def detached_to_persistent(self, session, instance): 

1880 """Intercept the "detached to persistent" transition for a specific object. 

1881 

1882 This event is a specialization of the 

1883 :meth:`.SessionEvents.after_attach` event which is only invoked 

1884 for this specific transition. It is invoked typically during the 

1885 :meth:`.Session.add` call, as well as during the 

1886 :meth:`.Session.delete` call if the object was not previously 

1887 associated with the 

1888 :class:`.Session` (note that an object marked as "deleted" remains 

1889 in the "persistent" state until the flush proceeds). 

1890 

1891 .. note:: 

1892 

1893 If the object becomes persistent as part of a call to 

1894 :meth:`.Session.delete`, the object is **not** yet marked as 

1895 deleted when this event is called. To detect deleted objects, 

1896 check the ``deleted`` flag sent to the 

1897 :meth:`.SessionEvents.persistent_to_detached` to event after the 

1898 flush proceeds, or check the :attr:`.Session.deleted` collection 

1899 within the :meth:`.SessionEvents.before_flush` event if deleted 

1900 objects need to be intercepted before the flush. 

1901 

1902 :param session: target :class:`.Session` 

1903 

1904 :param instance: the ORM-mapped instance being operated upon. 

1905 

1906 .. versionadded:: 1.1 

1907 

1908 .. seealso:: 

1909 

1910 :ref:`session_lifecycle_events` 

1911 

1912 """ 

1913 

1914 @_lifecycle_event 

1915 def loaded_as_persistent(self, session, instance): 

1916 """Intercept the "loaded as persistent" transition for a specific object. 

1917 

1918 This event is invoked within the ORM loading process, and is invoked 

1919 very similarly to the :meth:`.InstanceEvents.load` event. However, 

1920 the event here is linkable to a :class:`.Session` class or instance, 

1921 rather than to a mapper or class hierarchy, and integrates 

1922 with the other session lifecycle events smoothly. The object 

1923 is guaranteed to be present in the session's identity map when 

1924 this event is called. 

1925 

1926 .. note:: This event is invoked within the loader process before 

1927 eager loaders may have been completed, and the object's state may 

1928 not be complete. Additionally, invoking row-level refresh 

1929 operations on the object will place the object into a new loader 

1930 context, interfering with the existing load context. See the note 

1931 on :meth:`.InstanceEvents.load` for background on making use of the 

1932 :paramref:`.SessionEvents.restore_load_context` parameter, which 

1933 works in the same manner as that of 

1934 :paramref:`.InstanceEvents.restore_load_context`, in order to 

1935 resolve this scenario. 

1936 

1937 :param session: target :class:`.Session` 

1938 

1939 :param instance: the ORM-mapped instance being operated upon. 

1940 

1941 .. versionadded:: 1.1 

1942 

1943 .. seealso:: 

1944 

1945 :ref:`session_lifecycle_events` 

1946 

1947 """ 

1948 

1949 @_lifecycle_event 

1950 def persistent_to_deleted(self, session, instance): 

1951 """Intercept the "persistent to deleted" transition for a specific object. 

1952 

1953 This event is invoked when a persistent object's identity 

1954 is deleted from the database within a flush, however the object 

1955 still remains associated with the :class:`.Session` until the 

1956 transaction completes. 

1957 

1958 If the transaction is rolled back, the object moves again 

1959 to the persistent state, and the 

1960 :meth:`.SessionEvents.deleted_to_persistent` event is called. 

1961 If the transaction is committed, the object becomes detached, 

1962 which will emit the :meth:`.SessionEvents.deleted_to_detached` 

1963 event. 

1964 

1965 Note that while the :meth:`.Session.delete` method is the primary 

1966 public interface to mark an object as deleted, many objects 

1967 get deleted due to cascade rules, which are not always determined 

1968 until flush time. Therefore, there's no way to catch 

1969 every object that will be deleted until the flush has proceeded. 

1970 the :meth:`.SessionEvents.persistent_to_deleted` event is therefore 

1971 invoked at the end of a flush. 

1972 

1973 .. versionadded:: 1.1 

1974 

1975 .. seealso:: 

1976 

1977 :ref:`session_lifecycle_events` 

1978 

1979 """ 

1980 

1981 @_lifecycle_event 

1982 def deleted_to_persistent(self, session, instance): 

1983 """Intercept the "deleted to persistent" transition for a specific object. 

1984 

1985 This transition occurs only when an object that's been deleted 

1986 successfully in a flush is restored due to a call to 

1987 :meth:`.Session.rollback`. The event is not called under 

1988 any other circumstances. 

1989 

1990 .. versionadded:: 1.1 

1991 

1992 .. seealso:: 

1993 

1994 :ref:`session_lifecycle_events` 

1995 

1996 """ 

1997 

1998 @_lifecycle_event 

1999 def deleted_to_detached(self, session, instance): 

2000 """Intercept the "deleted to detached" transition for a specific object. 

2001 

2002 This event is invoked when a deleted object is evicted 

2003 from the session. The typical case when this occurs is when 

2004 the transaction for a :class:`.Session` in which the object 

2005 was deleted is committed; the object moves from the deleted 

2006 state to the detached state. 

2007 

2008 It is also invoked for objects that were deleted in a flush 

2009 when the :meth:`.Session.expunge_all` or :meth:`.Session.close` 

2010 events are called, as well as if the object is individually 

2011 expunged from its deleted state via :meth:`.Session.expunge`. 

2012 

2013 .. versionadded:: 1.1 

2014 

2015 .. seealso:: 

2016 

2017 :ref:`session_lifecycle_events` 

2018 

2019 """ 

2020 

2021 @_lifecycle_event 

2022 def persistent_to_detached(self, session, instance): 

2023 """Intercept the "persistent to detached" transition for a specific object. 

2024 

2025 This event is invoked when a persistent object is evicted 

2026 from the session. There are many conditions that cause this 

2027 to happen, including: 

2028 

2029 * using a method such as :meth:`.Session.expunge` 

2030 or :meth:`.Session.close` 

2031 

2032 * Calling the :meth:`.Session.rollback` method, when the object 

2033 was part of an INSERT statement for that session's transaction 

2034 

2035 

2036 :param session: target :class:`.Session` 

2037 

2038 :param instance: the ORM-mapped instance being operated upon. 

2039 

2040 :param deleted: boolean. If True, indicates this object moved 

2041 to the detached state because it was marked as deleted and flushed. 

2042 

2043 

2044 .. versionadded:: 1.1 

2045 

2046 .. seealso:: 

2047 

2048 :ref:`session_lifecycle_events` 

2049 

2050 """ 

2051 

2052 

2053class AttributeEvents(event.Events): 

2054 r"""Define events for object attributes. 

2055 

2056 These are typically defined on the class-bound descriptor for the 

2057 target class. 

2058 

2059 e.g.:: 

2060 

2061 from sqlalchemy import event 

2062 

2063 @event.listens_for(MyClass.collection, 'append', propagate=True) 

2064 def my_append_listener(target, value, initiator): 

2065 print("received append event for target: %s" % target) 

2066 

2067 

2068 Listeners have the option to return a possibly modified version of the 

2069 value, when the :paramref:`.AttributeEvents.retval` flag is passed to 

2070 :func:`.event.listen` or :func:`.event.listens_for`:: 

2071 

2072 def validate_phone(target, value, oldvalue, initiator): 

2073 "Strip non-numeric characters from a phone number" 

2074 

2075 return re.sub(r'\D', '', value) 

2076 

2077 # setup listener on UserContact.phone attribute, instructing 

2078 # it to use the return value 

2079 listen(UserContact.phone, 'set', validate_phone, retval=True) 

2080 

2081 A validation function like the above can also raise an exception 

2082 such as :exc:`ValueError` to halt the operation. 

2083 

2084 The :paramref:`.AttributeEvents.propagate` flag is also important when 

2085 applying listeners to mapped classes that also have mapped subclasses, 

2086 as when using mapper inheritance patterns:: 

2087 

2088 

2089 @event.listens_for(MySuperClass.attr, 'set', propagate=True) 

2090 def receive_set(target, value, initiator): 

2091 print("value set: %s" % target) 

2092 

2093 The full list of modifiers available to the :func:`.event.listen` 

2094 and :func:`.event.listens_for` functions are below. 

2095 

2096 :param active_history=False: When True, indicates that the 

2097 "set" event would like to receive the "old" value being 

2098 replaced unconditionally, even if this requires firing off 

2099 database loads. Note that ``active_history`` can also be 

2100 set directly via :func:`.column_property` and 

2101 :func:`_orm.relationship`. 

2102 

2103 :param propagate=False: When True, the listener function will 

2104 be established not just for the class attribute given, but 

2105 for attributes of the same name on all current subclasses 

2106 of that class, as well as all future subclasses of that 

2107 class, using an additional listener that listens for 

2108 instrumentation events. 

2109 :param raw=False: When True, the "target" argument to the 

2110 event will be the :class:`.InstanceState` management 

2111 object, rather than the mapped instance itself. 

2112 :param retval=False: when True, the user-defined event 

2113 listening must return the "value" argument from the 

2114 function. This gives the listening function the opportunity 

2115 to change the value that is ultimately used for a "set" 

2116 or "append" event. 

2117 

2118 """ 

2119 

2120 _target_class_doc = "SomeClass.some_attribute" 

2121 _dispatch_target = QueryableAttribute 

2122 

2123 @staticmethod 

2124 def _set_dispatch(cls, dispatch_cls): 

2125 dispatch = event.Events._set_dispatch(cls, dispatch_cls) 

2126 dispatch_cls._active_history = False 

2127 return dispatch 

2128 

2129 @classmethod 

2130 def _accept_with(cls, target): 

2131 # TODO: coverage 

2132 if isinstance(target, interfaces.MapperProperty): 

2133 return getattr(target.parent.class_, target.key) 

2134 else: 

2135 return target 

2136 

2137 @classmethod 

2138 def _listen( 

2139 cls, 

2140 event_key, 

2141 active_history=False, 

2142 raw=False, 

2143 retval=False, 

2144 propagate=False, 

2145 ): 

2146 

2147 target, fn = event_key.dispatch_target, event_key._listen_fn 

2148 

2149 if active_history: 

2150 target.dispatch._active_history = True 

2151 

2152 if not raw or not retval: 

2153 

2154 def wrap(target, *arg): 

2155 if not raw: 

2156 target = target.obj() 

2157 if not retval: 

2158 if arg: 

2159 value = arg[0] 

2160 else: 

2161 value = None 

2162 fn(target, *arg) 

2163 return value 

2164 else: 

2165 return fn(target, *arg) 

2166 

2167 event_key = event_key.with_wrapper(wrap) 

2168 

2169 event_key.base_listen(propagate=propagate) 

2170 

2171 if propagate: 

2172 manager = instrumentation.manager_of_class(target.class_) 

2173 

2174 for mgr in manager.subclass_managers(True): 

2175 event_key.with_dispatch_target(mgr[target.key]).base_listen( 

2176 propagate=True 

2177 ) 

2178 if active_history: 

2179 mgr[target.key].dispatch._active_history = True 

2180 

2181 def append(self, target, value, initiator): 

2182 """Receive a collection append event. 

2183 

2184 The append event is invoked for each element as it is appended 

2185 to the collection. This occurs for single-item appends as well 

2186 as for a "bulk replace" operation. 

2187 

2188 :param target: the object instance receiving the event. 

2189 If the listener is registered with ``raw=True``, this will 

2190 be the :class:`.InstanceState` object. 

2191 :param value: the value being appended. If this listener 

2192 is registered with ``retval=True``, the listener 

2193 function must return this value, or a new value which 

2194 replaces it. 

2195 :param initiator: An instance of :class:`.attributes.Event` 

2196 representing the initiation of the event. May be modified 

2197 from its original value by backref handlers in order to control 

2198 chained event propagation, as well as be inspected for information 

2199 about the source of the event. 

2200 :return: if the event was registered with ``retval=True``, 

2201 the given value, or a new effective value, should be returned. 

2202 

2203 .. seealso:: 

2204 

2205 :class:`.AttributeEvents` - background on listener options such 

2206 as propagation to subclasses. 

2207 

2208 :meth:`.AttributeEvents.bulk_replace` 

2209 

2210 """ 

2211 

2212 def bulk_replace(self, target, values, initiator): 

2213 """Receive a collection 'bulk replace' event. 

2214 

2215 This event is invoked for a sequence of values as they are incoming 

2216 to a bulk collection set operation, which can be 

2217 modified in place before the values are treated as ORM objects. 

2218 This is an "early hook" that runs before the bulk replace routine 

2219 attempts to reconcile which objects are already present in the 

2220 collection and which are being removed by the net replace operation. 

2221 

2222 It is typical that this method be combined with use of the 

2223 :meth:`.AttributeEvents.append` event. When using both of these 

2224 events, note that a bulk replace operation will invoke 

2225 the :meth:`.AttributeEvents.append` event for all new items, 

2226 even after :meth:`.AttributeEvents.bulk_replace` has been invoked 

2227 for the collection as a whole. In order to determine if an 

2228 :meth:`.AttributeEvents.append` event is part of a bulk replace, 

2229 use the symbol :attr:`~.attributes.OP_BULK_REPLACE` to test the 

2230 incoming initiator:: 

2231 

2232 from sqlalchemy.orm.attributes import OP_BULK_REPLACE 

2233 

2234 @event.listens_for(SomeObject.collection, "bulk_replace") 

2235 def process_collection(target, values, initiator): 

2236 values[:] = [_make_value(value) for value in values] 

2237 

2238 @event.listens_for(SomeObject.collection, "append", retval=True) 

2239 def process_collection(target, value, initiator): 

2240 # make sure bulk_replace didn't already do it 

2241 if initiator is None or initiator.op is not OP_BULK_REPLACE: 

2242 return _make_value(value) 

2243 else: 

2244 return value 

2245 

2246 .. versionadded:: 1.2 

2247 

2248 :param target: the object instance receiving the event. 

2249 If the listener is registered with ``raw=True``, this will 

2250 be the :class:`.InstanceState` object. 

2251 :param value: a sequence (e.g. a list) of the values being set. The 

2252 handler can modify this list in place. 

2253 :param initiator: An instance of :class:`.attributes.Event` 

2254 representing the initiation of the event. 

2255 

2256 .. seealso:: 

2257 

2258 :class:`.AttributeEvents` - background on listener options such 

2259 as propagation to subclasses. 

2260 

2261 

2262 """ 

2263 

2264 def remove(self, target, value, initiator): 

2265 """Receive a collection remove event. 

2266 

2267 :param target: the object instance receiving the event. 

2268 If the listener is registered with ``raw=True``, this will 

2269 be the :class:`.InstanceState` object. 

2270 :param value: the value being removed. 

2271 :param initiator: An instance of :class:`.attributes.Event` 

2272 representing the initiation of the event. May be modified 

2273 from its original value by backref handlers in order to control 

2274 chained event propagation. 

2275 

2276 .. versionchanged:: 0.9.0 the ``initiator`` argument is now 

2277 passed as a :class:`.attributes.Event` object, and may be 

2278 modified by backref handlers within a chain of backref-linked 

2279 events. 

2280 

2281 :return: No return value is defined for this event. 

2282 

2283 

2284 .. seealso:: 

2285 

2286 :class:`.AttributeEvents` - background on listener options such 

2287 as propagation to subclasses. 

2288 

2289 """ 

2290 

2291 def set(self, target, value, oldvalue, initiator): 

2292 """Receive a scalar set event. 

2293 

2294 :param target: the object instance receiving the event. 

2295 If the listener is registered with ``raw=True``, this will 

2296 be the :class:`.InstanceState` object. 

2297 :param value: the value being set. If this listener 

2298 is registered with ``retval=True``, the listener 

2299 function must return this value, or a new value which 

2300 replaces it. 

2301 :param oldvalue: the previous value being replaced. This 

2302 may also be the symbol ``NEVER_SET`` or ``NO_VALUE``. 

2303 If the listener is registered with ``active_history=True``, 

2304 the previous value of the attribute will be loaded from 

2305 the database if the existing value is currently unloaded 

2306 or expired. 

2307 :param initiator: An instance of :class:`.attributes.Event` 

2308 representing the initiation of the event. May be modified 

2309 from its original value by backref handlers in order to control 

2310 chained event propagation. 

2311 

2312 .. versionchanged:: 0.9.0 the ``initiator`` argument is now 

2313 passed as a :class:`.attributes.Event` object, and may be 

2314 modified by backref handlers within a chain of backref-linked 

2315 events. 

2316 

2317 :return: if the event was registered with ``retval=True``, 

2318 the given value, or a new effective value, should be returned. 

2319 

2320 .. seealso:: 

2321 

2322 :class:`.AttributeEvents` - background on listener options such 

2323 as propagation to subclasses. 

2324 

2325 """ 

2326 

2327 def init_scalar(self, target, value, dict_): 

2328 r"""Receive a scalar "init" event. 

2329 

2330 This event is invoked when an uninitialized, unpersisted scalar 

2331 attribute is accessed, e.g. read:: 

2332 

2333 

2334 x = my_object.some_attribute 

2335 

2336 The ORM's default behavior when this occurs for an un-initialized 

2337 attribute is to return the value ``None``; note this differs from 

2338 Python's usual behavior of raising ``AttributeError``. The 

2339 event here can be used to customize what value is actually returned, 

2340 with the assumption that the event listener would be mirroring 

2341 a default generator that is configured on the Core 

2342 :class:`_schema.Column` 

2343 object as well. 

2344 

2345 Since a default generator on a :class:`_schema.Column` 

2346 might also produce 

2347 a changing value such as a timestamp, the 

2348 :meth:`.AttributeEvents.init_scalar` 

2349 event handler can also be used to **set** the newly returned value, so 

2350 that a Core-level default generation function effectively fires off 

2351 only once, but at the moment the attribute is accessed on the 

2352 non-persisted object. Normally, no change to the object's state 

2353 is made when an uninitialized attribute is accessed (much older 

2354 SQLAlchemy versions did in fact change the object's state). 

2355 

2356 If a default generator on a column returned a particular constant, 

2357 a handler might be used as follows:: 

2358 

2359 SOME_CONSTANT = 3.1415926 

2360 

2361 class MyClass(Base): 

2362 # ... 

2363 

2364 some_attribute = Column(Numeric, default=SOME_CONSTANT) 

2365 

2366 @event.listens_for( 

2367 MyClass.some_attribute, "init_scalar", 

2368 retval=True, propagate=True) 

2369 def _init_some_attribute(target, dict_, value): 

2370 dict_['some_attribute'] = SOME_CONSTANT 

2371 return SOME_CONSTANT 

2372 

2373 Above, we initialize the attribute ``MyClass.some_attribute`` to the 

2374 value of ``SOME_CONSTANT``. The above code includes the following 

2375 features: 

2376 

2377 * By setting the value ``SOME_CONSTANT`` in the given ``dict_``, 

2378 we indicate that this value is to be persisted to the database. 

2379 This supersedes the use of ``SOME_CONSTANT`` in the default generator 

2380 for the :class:`_schema.Column`. The ``active_column_defaults.py`` 

2381 example given at :ref:`examples_instrumentation` illustrates using 

2382 the same approach for a changing default, e.g. a timestamp 

2383 generator. In this particular example, it is not strictly 

2384 necessary to do this since ``SOME_CONSTANT`` would be part of the 

2385 INSERT statement in either case. 

2386 

2387 * By establishing the ``retval=True`` flag, the value we return 

2388 from the function will be returned by the attribute getter. 

2389 Without this flag, the event is assumed to be a passive observer 

2390 and the return value of our function is ignored. 

2391 

2392 * The ``propagate=True`` flag is significant if the mapped class 

2393 includes inheriting subclasses, which would also make use of this 

2394 event listener. Without this flag, an inheriting subclass will 

2395 not use our event handler. 

2396 

2397 In the above example, the attribute set event 

2398 :meth:`.AttributeEvents.set` as well as the related validation feature 

2399 provided by :obj:`_orm.validates` is **not** invoked when we apply our 

2400 value to the given ``dict_``. To have these events to invoke in 

2401 response to our newly generated value, apply the value to the given 

2402 object as a normal attribute set operation:: 

2403 

2404 SOME_CONSTANT = 3.1415926 

2405 

2406 @event.listens_for( 

2407 MyClass.some_attribute, "init_scalar", 

2408 retval=True, propagate=True) 

2409 def _init_some_attribute(target, dict_, value): 

2410 # will also fire off attribute set events 

2411 target.some_attribute = SOME_CONSTANT 

2412 return SOME_CONSTANT 

2413 

2414 When multiple listeners are set up, the generation of the value 

2415 is "chained" from one listener to the next by passing the value 

2416 returned by the previous listener that specifies ``retval=True`` 

2417 as the ``value`` argument of the next listener. 

2418 

2419 .. versionadded:: 1.1 

2420 

2421 :param target: the object instance receiving the event. 

2422 If the listener is registered with ``raw=True``, this will 

2423 be the :class:`.InstanceState` object. 

2424 :param value: the value that is to be returned before this event 

2425 listener were invoked. This value begins as the value ``None``, 

2426 however will be the return value of the previous event handler 

2427 function if multiple listeners are present. 

2428 :param dict\_: the attribute dictionary of this mapped object. 

2429 This is normally the ``__dict__`` of the object, but in all cases 

2430 represents the destination that the attribute system uses to get 

2431 at the actual value of this attribute. Placing the value in this 

2432 dictionary has the effect that the value will be used in the 

2433 INSERT statement generated by the unit of work. 

2434 

2435 

2436 .. seealso:: 

2437 

2438 :class:`.AttributeEvents` - background on listener options such 

2439 as propagation to subclasses. 

2440 

2441 :ref:`examples_instrumentation` - see the 

2442 ``active_column_defaults.py`` example. 

2443 

2444 """ 

2445 

2446 def init_collection(self, target, collection, collection_adapter): 

2447 """Receive a 'collection init' event. 

2448 

2449 This event is triggered for a collection-based attribute, when 

2450 the initial "empty collection" is first generated for a blank 

2451 attribute, as well as for when the collection is replaced with 

2452 a new one, such as via a set event. 

2453 

2454 E.g., given that ``User.addresses`` is a relationship-based 

2455 collection, the event is triggered here:: 

2456 

2457 u1 = User() 

2458 u1.addresses.append(a1) # <- new collection 

2459 

2460 and also during replace operations:: 

2461 

2462 u1.addresses = [a2, a3] # <- new collection 

2463 

2464 :param target: the object instance receiving the event. 

2465 If the listener is registered with ``raw=True``, this will 

2466 be the :class:`.InstanceState` object. 

2467 :param collection: the new collection. This will always be generated 

2468 from what was specified as 

2469 :paramref:`_orm.relationship.collection_class`, and will always 

2470 be empty. 

2471 :param collection_adapter: the :class:`.CollectionAdapter` that will 

2472 mediate internal access to the collection. 

2473 

2474 .. versionadded:: 1.0.0 the :meth:`.AttributeEvents.init_collection` 

2475 and :meth:`.AttributeEvents.dispose_collection` events supersede 

2476 the :class:`.orm.collection.linker` hook. 

2477 

2478 .. seealso:: 

2479 

2480 :class:`.AttributeEvents` - background on listener options such 

2481 as propagation to subclasses. 

2482 

2483 """ 

2484 

2485 def dispose_collection(self, target, collection, collection_adapter): 

2486 """Receive a 'collection dispose' event. 

2487 

2488 This event is triggered for a collection-based attribute when 

2489 a collection is replaced, that is:: 

2490 

2491 u1.addresses.append(a1) 

2492 

2493 u1.addresses = [a2, a3] # <- old collection is disposed 

2494 

2495 The old collection received will contain its previous contents. 

2496 

2497 .. versionchanged:: 1.2 The collection passed to 

2498 :meth:`.AttributeEvents.dispose_collection` will now have its 

2499 contents before the dispose intact; previously, the collection 

2500 would be empty. 

2501 

2502 .. versionadded:: 1.0.0 the :meth:`.AttributeEvents.init_collection` 

2503 and :meth:`.AttributeEvents.dispose_collection` events supersede 

2504 the :class:`.collection.linker` hook. 

2505 

2506 .. seealso:: 

2507 

2508 :class:`.AttributeEvents` - background on listener options such 

2509 as propagation to subclasses. 

2510 

2511 """ 

2512 

2513 def modified(self, target, initiator): 

2514 """Receive a 'modified' event. 

2515 

2516 This event is triggered when the :func:`.attributes.flag_modified` 

2517 function is used to trigger a modify event on an attribute without 

2518 any specific value being set. 

2519 

2520 .. versionadded:: 1.2 

2521 

2522 :param target: the object instance receiving the event. 

2523 If the listener is registered with ``raw=True``, this will 

2524 be the :class:`.InstanceState` object. 

2525 

2526 :param initiator: An instance of :class:`.attributes.Event` 

2527 representing the initiation of the event. 

2528 

2529 .. seealso:: 

2530 

2531 :class:`.AttributeEvents` - background on listener options such 

2532 as propagation to subclasses. 

2533 

2534 """ 

2535 

2536 

2537class QueryEvents(event.Events): 

2538 """Represent events within the construction of a :class:`_query.Query` 

2539 object. 

2540 

2541 The events here are intended to be used with an as-yet-unreleased 

2542 inspection system for :class:`_query.Query`. Some very basic operations 

2543 are possible now, however the inspection system is intended to allow 

2544 complex query manipulations to be automated. 

2545 

2546 .. versionadded:: 1.0.0 

2547 

2548 """ 

2549 

2550 _target_class_doc = "SomeQuery" 

2551 _dispatch_target = Query 

2552 

2553 def before_compile(self, query): 

2554 """Receive the :class:`_query.Query` 

2555 object before it is composed into a 

2556 core :class:`_expression.Select` object. 

2557 

2558 This event is intended to allow changes to the query given:: 

2559 

2560 @event.listens_for(Query, "before_compile", retval=True) 

2561 def no_deleted(query): 

2562 for desc in query.column_descriptions: 

2563 if desc['type'] is User: 

2564 entity = desc['entity'] 

2565 query = query.filter(entity.deleted == False) 

2566 return query 

2567 

2568 The event should normally be listened with the ``retval=True`` 

2569 parameter set, so that the modified query may be returned. 

2570 

2571 The :meth:`.QueryEvents.before_compile` event by default 

2572 will disallow "baked" queries from caching a query, if the event 

2573 hook returns a new :class:`_query.Query` object. 

2574 This affects both direct 

2575 use of the baked query extension as well as its operation within 

2576 lazy loaders and eager loaders for relationships. In order to 

2577 re-establish the query being cached, apply the event adding the 

2578 ``bake_ok`` flag:: 

2579 

2580 @event.listens_for( 

2581 Query, "before_compile", retval=True, bake_ok=True) 

2582 def my_event(query): 

2583 for desc in query.column_descriptions: 

2584 if desc['type'] is User: 

2585 entity = desc['entity'] 

2586 query = query.filter(entity.deleted == False) 

2587 return query 

2588 

2589 When ``bake_ok`` is set to True, the event hook will only be invoked 

2590 once, and not called for subsequent invocations of a particular query 

2591 that is being cached. 

2592 

2593 .. versionadded:: 1.3.11 - added the "bake_ok" flag to the 

2594 :meth:`.QueryEvents.before_compile` event and disallowed caching via 

2595 the "baked" extension from occurring for event handlers that 

2596 return a new :class:`_query.Query` object if this flag is not set. 

2597 

2598 .. seealso:: 

2599 

2600 :meth:`.QueryEvents.before_compile_update` 

2601 

2602 :meth:`.QueryEvents.before_compile_delete` 

2603 

2604 :ref:`baked_with_before_compile` 

2605 

2606 """ 

2607 

2608 def before_compile_update(self, query, update_context): 

2609 """Allow modifications to the :class:`_query.Query` object within 

2610 :meth:`_query.Query.update`. 

2611 

2612 Like the :meth:`.QueryEvents.before_compile` event, if the event 

2613 is to be used to alter the :class:`_query.Query` object, it should 

2614 be configured with ``retval=True``, and the modified 

2615 :class:`_query.Query` object returned, as in :: 

2616 

2617 @event.listens_for(Query, "before_compile_update", retval=True) 

2618 def no_deleted(query, update_context): 

2619 for desc in query.column_descriptions: 

2620 if desc['type'] is User: 

2621 entity = desc['entity'] 

2622 query = query.filter(entity.deleted == False) 

2623 

2624 update_context.values['timestamp'] = datetime.utcnow() 

2625 return query 

2626 

2627 The ``.values`` dictionary of the "update context" object can also 

2628 be modified in place as illustrated above. 

2629 

2630 :param query: a :class:`_query.Query` instance; this is also 

2631 the ``.query`` attribute of the given "update context" 

2632 object. 

2633 

2634 :param update_context: an "update context" object which is 

2635 the same kind of object as described in 

2636 :paramref:`.QueryEvents.after_bulk_update.update_context`. 

2637 The object has a ``.values`` attribute in an UPDATE context which is 

2638 the dictionary of parameters passed to :meth:`_query.Query.update`. 

2639 This 

2640 dictionary can be modified to alter the VALUES clause of the 

2641 resulting UPDATE statement. 

2642 

2643 .. versionadded:: 1.2.17 

2644 

2645 .. seealso:: 

2646 

2647 :meth:`.QueryEvents.before_compile` 

2648 

2649 :meth:`.QueryEvents.before_compile_delete` 

2650 

2651 

2652 """ 

2653 

2654 def before_compile_delete(self, query, delete_context): 

2655 """Allow modifications to the :class:`_query.Query` object within 

2656 :meth:`_query.Query.delete`. 

2657 

2658 Like the :meth:`.QueryEvents.before_compile` event, this event 

2659 should be configured with ``retval=True``, and the modified 

2660 :class:`_query.Query` object returned, as in :: 

2661 

2662 @event.listens_for(Query, "before_compile_delete", retval=True) 

2663 def no_deleted(query, delete_context): 

2664 for desc in query.column_descriptions: 

2665 if desc['type'] is User: 

2666 entity = desc['entity'] 

2667 query = query.filter(entity.deleted == False) 

2668 return query 

2669 

2670 :param query: a :class:`_query.Query` instance; this is also 

2671 the ``.query`` attribute of the given "delete context" 

2672 object. 

2673 

2674 :param delete_context: a "delete context" object which is 

2675 the same kind of object as described in 

2676 :paramref:`.QueryEvents.after_bulk_delete.delete_context`. 

2677 

2678 .. versionadded:: 1.2.17 

2679 

2680 .. seealso:: 

2681 

2682 :meth:`.QueryEvents.before_compile` 

2683 

2684 :meth:`.QueryEvents.before_compile_update` 

2685 

2686 

2687 """ 

2688 

2689 @classmethod 

2690 def _listen(cls, event_key, retval=False, bake_ok=False, **kw): 

2691 fn = event_key._listen_fn 

2692 

2693 if not retval: 

2694 

2695 def wrap(*arg, **kw): 

2696 if not retval: 

2697 query = arg[0] 

2698 fn(*arg, **kw) 

2699 return query 

2700 else: 

2701 return fn(*arg, **kw) 

2702 

2703 event_key = event_key.with_wrapper(wrap) 

2704 else: 

2705 # don't assume we can apply an attribute to the callable 

2706 def wrap(*arg, **kw): 

2707 return fn(*arg, **kw) 

2708 

2709 event_key = event_key.with_wrapper(wrap) 

2710 

2711 wrap._bake_ok = bake_ok 

2712 

2713 event_key.base_listen(**kw)