Participer au site avec un Tip
Rechercher
 

Améliorations / Corrections

Vous avez des améliorations (ou des corrections) à proposer pour ce document : je vous remerçie par avance de m'en faire part, cela m'aide à améliorer le site.

Emplacement :

Description des améliorations :

Vous êtes un professionnel et vous avez besoin d'une formation ? Coder avec une
Intelligence Artificielle
Voir le programme détaillé
Module « sqlalchemy.orm »

Classe « sessionmaker »

Informations générales

Héritage

builtins.object
    Generic
builtins.object
    _SessionClassMethods
        sessionmaker

Définition

class sessionmaker(_SessionClassMethods, Generic):

help(sessionmaker)

A configurable :class:`.Session` factory.

The :class:`.sessionmaker` factory generates new
:class:`.Session` objects when called, creating them given
the configurational arguments established here.

e.g.::

    from sqlalchemy import create_engine
    from sqlalchemy.orm import sessionmaker

    # an Engine, which the Session will use for connection
    # resources
    engine = create_engine("postgresql+psycopg2://scott:tiger@localhost/")

    Session = sessionmaker(engine)

    with Session() as session:
        session.add(some_object)
        session.add(some_other_object)
        session.commit()

Context manager use is optional; otherwise, the returned
:class:`_orm.Session` object may be closed explicitly via the
:meth:`_orm.Session.close` method.   Using a
``try:/finally:`` block is optional, however will ensure that the close
takes place even if there are database errors::

    session = Session()
    try:
        session.add(some_object)
        session.add(some_other_object)
        session.commit()
    finally:
        session.close()

:class:`.sessionmaker` acts as a factory for :class:`_orm.Session`
objects in the same way as an :class:`_engine.Engine` acts as a factory
for :class:`_engine.Connection` objects.  In this way it also includes
a :meth:`_orm.sessionmaker.begin` method, that provides a context
manager which both begins and commits a transaction, as well as closes
out the :class:`_orm.Session` when complete, rolling back the transaction
if any errors occur::

    Session = sessionmaker(engine)

    with Session.begin() as session:
        session.add(some_object)
        session.add(some_other_object)
    # commits transaction, closes session

.. versionadded:: 1.4

When calling upon :class:`_orm.sessionmaker` to construct a
:class:`_orm.Session`, keyword arguments may also be passed to the
method; these arguments will override that of the globally configured
parameters.  Below we use a :class:`_orm.sessionmaker` bound to a certain
:class:`_engine.Engine` to produce a :class:`_orm.Session` that is instead
bound to a specific :class:`_engine.Connection` procured from that engine::

    Session = sessionmaker(engine)

    # bind an individual session to a connection

    with engine.connect() as connection:
        with Session(bind=connection) as session:
            ...  # work with session

The class also includes a method :meth:`_orm.sessionmaker.configure`, which
can be used to specify additional keyword arguments to the factory, which
will take effect for subsequent :class:`.Session` objects generated. This
is usually used to associate one or more :class:`_engine.Engine` objects
with an existing
:class:`.sessionmaker` factory before it is first used::

    # application starts, sessionmaker does not have
    # an engine bound yet
    Session = sessionmaker()

    # ... later, when an engine URL is read from a configuration
    # file or other events allow the engine to be created
    engine = create_engine("sqlite:///foo.db")
    Session.configure(bind=engine)

    sess = Session()
    # work with session

.. seealso::

    :ref:`session_getting` - introductory text on creating
    sessions using :class:`.sessionmaker`.

Constructeur(s)

Signature du constructeur Description
__init__(self, bind: 'Optional[_SessionBind]' = None, *, class_: 'Type[_S]' = <class 'sqlalchemy.orm.session.Session'>, autoflush: 'bool' = True, expire_on_commit: 'bool' = True, info: 'Optional[_InfoType]' = None, **kw: 'Any') Construct a new :class:`.sessionmaker`. [extrait de __init__.__doc__]

Liste des opérateurs

Opérateurs hérités de la classe object

__eq__, __ge__, __gt__, __le__, __lt__, __ne__

Liste des méthodes

Toutes les méthodes Méthodes d'instance Méthodes statiques Méthodes dépréciées
Signature de la méthodeDescription
__call__(self, **local_kw: 'Any') -> '_S' Produce a new :class:`.Session` object using the configuration [extrait de __call__.__doc__]
__class_getitem__ Parameterizes a generic class. [extrait de __class_getitem__.__doc__]
__repr__(self) -> 'str'
begin(self) -> 'contextlib.AbstractContextManager[_S]' Produce a context manager that both provides a new [extrait de begin.__doc__]
configure(self, **new_kw: 'Any') -> 'None' (Re)configure the arguments for this sessionmaker. [extrait de configure.__doc__]

Méthodes héritées de la classe Generic

__init_subclass__, __subclasshook__

Méthodes héritées de la classe _SessionClassMethods

__init_subclass__, __subclasshook__, close_all, identity_key, object_session

Méthodes héritées de la classe object

__delattr__, __dir__, __format__, __getattribute__, __getstate__, __hash__, __reduce__, __reduce_ex__, __setattr__, __sizeof__, __str__

Vous êtes un professionnel et vous avez besoin d'une formation ? Calcul scientifique
avec Python
Voir le programme détaillé