Python ORM Framework SQLAlchemy Learning Notes mapping classes use instances and session sessions to introduce _python

Source: Internet
Author: User
Tags sessions

1. Create an instance of the mapping Class (Instance)

As we've described how to map a database entity table to a Python class, we can create an instance of this class (Instance), or, for example, the user class in a previous article, let's create a user object:

Copy Code code as follows:

>>> ed_user = User (' Ed ', ' Ed Jones ', ' Edspassword ')
>>> Ed_user.name
' Ed '
>>> Ed_user.password
' Edspassword '
>>> Str (ed_user.id)
' None '

Instantiated like the ordinary Python class, you might ask why Ed_user.id is the None value, first ID this attribute is not initialized by the __init__ () constructor, so the default is because of the previously defined ORM ID column (column) Produces a none value, by default, ORM creates class attributes for all mapped table columns, which are implemented through the descriptor (descriptors) mechanism in the Python language. So the use of these properties can include some additional behavior, including tracking changes, or automatically loading new data from the database when needed, which means that when we use these attributes, including modification or reading, it triggers a series of actions within the ORM.


Wait, you haven't said understand why ID this attribute is a none value. Oh, in fact, we do not insert data into the database, the general primary key this property will automatically generate a duplicate value when inserting the database to ensure uniqueness. Since we do not persist objects (Persist) (the so-called persistence is to store the object data in the database according to the mapping relationship), the ID value here is none. Don't worry, later when we introduce the data to be persisted you can see a new automatically generated ID.

Next little lazy, introduce a lazy skills:-)

What if we don't define the construction method of the Mapping class __init__ () have any adverse effects? Not at all, sqlalchemy for us to consider this, if we were lazy to define the previous user class as this:

Copy Code code as follows:

Class User (Base):
__tablename__ = ' users '
id = Column (Integer, Primary_key=true)
Name = Column (String)
FullName = Column (String)
Password = Column (String)

Because the user inherits from base (the base definition sees an article), it is managed by the declarative system, and the declarative system discovers that this class lacks a construction method, so it is friendly to make up a construction method, Of course, the construction method provided cannot use positional parameter access as we define our own constructs, and it is recommended that you use key-based parameter access methods, including all of our columns that are mapped with column definitions, such as the following:
Copy Code code as follows:

u1 = User (name= ' Ed ', Fullname= ' Ed Jones ', password= ' Foobar ')

IDs can also be passed in, and typically these primary keys are automatically maintained by the system, and we don't need to assign a value to them.

2. Create and use sessions (session)

Here is "everything is ready, only the east wind," in the official document, said "We are now prepared and the database ' Talk '" (We are ready to the "talking"). An ORM action handle (Handle) is called a session. In order to use the session, we need to configure it first, and the code statements that configure the sessions should be at a level of code (together) with the code statement of the Create_engine () creation engine.

For example, we use Create_engine () first to build engine name for engine (the engine code can refer to my first article), and then use the Sessionmaker () factory function to establish the session class, while binding our existing engine, For example, the code is as follows:

Copy Code code as follows:

>>> from Sqlalchemy.orm import Sessionmaker
>>> session = Sessionmaker (Bind=engine)

If we create the session code and the code to create the engine is not at a level, such as first Sessionmaker () A class of sessions, and then use Create_engine () to create the engine, So do we have a chance to bind the session and the engine together? Of course, we can use the Configure method of the session class to configure the engine bindings, such as:
Copy Code code as follows:

Session = Sessionmaker ()
# engine = Create_engine (...) Create engine
Session.configure (Bind=engine) # to be here engine should have been created

The session class created here through the Sessionmaker () factory should bind the engine we created earlier, but the conversation has not really started, and we need to instantiate the session class to begin the conversation:
Copy Code code as follows:

>>> session = Session ()

Here the session gets the database connection pool maintained by engine, and it maintains the mapped data in memory until commit changes are committed or the conversation object is closed.

The establishment of the session here is finished, next will explain the real ORM database query part, welcome attention!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.