Python ORM framework SQLAlchemy learning notes mapping class using examples and Session sessions

  • 2020-04-02 13:43:07
  • OfStack

1. Create Instance of the mapped class

Previously, we introduced how to map database entity table to Python class. Now, we can create an Instance of this class. We will take the User class of the previous article as an example.


>>> ed_user = User('ed', 'Ed Jones', 'edspassword')
>>> ed_user.name
'ed'
>>> ed_user.password
'edspassword'
>>> str(ed_user.id)
'None'

Like regular Python class instantiation, you might ask why ed_user. Id would be a value of None, first of all, id this property does not pass __init__ () method to construct the initialization, so the default will be because of the previously defined ORM id Column (Column) to generate a value of None, by default, the ORM will be mapping table columns to create for all class properties, these properties is the descriptor (Descriptors) through the Python language mechanism. So the use of these properties involves some additional behavior, including tracking changes, or automatically loading new data from the database when needed, which means that when we use these properties, including modifications or reads, we trigger a series of actions within the ORM.


Wait, you still didn't say understand why id this property to a value of None. Well, in fact, we do not insert data into the database, in general, the primary key this property will be inserted into the database automatically generated a non-repeat value to ensure the uniqueness. The id value is None because we did not Persist the object (Persist is the mapping of the object data into the database). Don't worry, you'll see a new auto-generated id later when we talk about persisting the data.

Here's a little bit of a lazy trick :-)

Is there any harm if we don't define the constructor of the mapped class with s/s ()? Not at all. SQLAlchemy takes this into account for us, if we were lazy and defined the previous User class like this:


class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)
    password = Column(String)

Due to User inherits from the Base (Base definition see an article on), so the Declarative system management, the Declarative found this class lack of structure system, and so is very friendly to us to fill in a constructor, and of course with the constructor is not like our own constructor defined using access based on the location of the parameters, it is recommended to use access method based on the key parameters, including the definition of we all use the Column mapping columns, such as the following ways:

u1 = User(name='ed', fullname='Ed Jones', password='foobar')

Id can also be passed in, and in general, such primary keys are maintained automatically by the system, so we don't need to assign a value to them.

2. Create and use sessions

At this point, "everything is ready except the wind," in the words of the official document, "We're now ready to start talking to the database." The Handle of an ORM operation is called a Session. In order to use the Session, we need to configure it first, and the code statements that configure the Session should be at the same code level as the code statements that create the create_engine() engine.

For example, we use create_engine() to first build the engine name as engine(the engine building code can refer to my first article), and then use the sessionmaker() factory function to build the Session class, and bind our existing engine, such as the following code:


>>> from sqlalchemy.orm import sessionmaker
>>> Session = sessionmaker(bind=engine)

What if we created the Session at a different level than we created the engine, such as a sessionmaker() Session class, and then created the engine with create_engine()? Of course, we can configure the engine binding using the configure method of the Session class, such as:

Session = sessionmaker()
# engine = create_engine(...)  Create the engine 
Session.configure(bind=engine)  #  here engine It should have been created 

At this point, the Session class created by the sessionmaker () factory should bind to the Engine we created earlier, but the Session has not really started yet. To start the Session, we need to instantiate the Session class:

>>> session = Session()

This session captures the database connection pool maintained by the Engine and maintains the mapped data in memory until a commit change or closes the session object.

Here is the session to establish the end of the explanation, the next section will explain the real ORM database query, welcome to pay attention!


Related articles: