Python ORM Framework SQLAlchemy Learning Note Mapping class usage examples and session sessions introduction

Source: Internet
Author: User
1. Creating an instance of the mapping Class (Instance)

Before we describe 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 of a previous article, let's create a user object:
Copy the Code code as follows:


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


As with the normal Python class, you might ask why Ed_user.id is the None value, first the id attribute is not initialized by the __init__ () constructor, so by default the ID column (column) of the previously defined ORM Instead of a value of None, Orm creates class properties for all mapped table columns by default, which are implemented through the Python language descriptor (descriptors) mechanism. So the use of these properties will include some extra behavior, including tracking changes, or automatically loading new data from the database when needed, meaning that when we use these properties, including modification or reading, we trigger a series of actions inside the ORM.


Wait, you haven't said why ID this attribute will be the none value. Well, in fact, we do not insert data into the database, the general primary key this property will automatically produce a distinct value to ensure uniqueness when inserting the database. Since we do not persist the object (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, you'll see a new auto-generated ID later when we describe persisting the data.

Next little lazy, introduce a lazy skill:-)

What if we do not define the construction method of the Mapping class __init__ () will have any adverse effect? Not at all, sqlalchemy for us to consider this, if we lazy to define the previous user class as:
Copy the 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 user inherits from base (base definition see previous article), so by the management of the declarative system, the declarative system found that this class lacks the construction method, so very friendly to us to fill up a construction method, Of course, the construction method provided does not use location-based parameter access as defined by our own construction method, it is recommended to use key-based parameter access, including all of our columns with column definition mappings, such as the following:
Copy CodeThe code is as follows:


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


IDs can also be passed in, in the sense that such primary keys are automatically maintained by the system, and we do not need to assign values to them.

2. Create and use sessions (session)

"Everything is ready, only the east wind," said the official document, "We are now prepared to talk to the database '" (We're OK to start talking to the databases). An ORM's manipulation handle (Handle) is called a session. In order to use the session, we need to configure it first, and the code statement that configures the session should be the code statement for the Create_engine () creation engine at one level of code (put together on the line).

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


>>> from Sqlalchemy.orm import Sessionmaker
>>> Session = Sessionmaker (bind=engine)


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


Session = Sessionmaker ()
# engine = Create_engine (...) Creating engines
Session.configure (bind=engine) # Here the engine should have been created


The session class created here through the Sessionmaker () factory should be bound to the engine we created earlier, but the conversation has not really started and we need to instantiate this session class to start the conversation:
Copy CodeThe code is as follows:


>>> session = Session ()


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

The establishment of the conversation here will be explained, the next step is to explain the real ORM database query part, welcome attention!

  • 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.