Python ORM framework SQLAlchemy learning note ing Class usage instance and Session Introduction

Source: Internet
Author: User

1. Create a ing Instance)

We have introduced how to map database entity tables to Python classes. Now we can create an Instance for this class. We are still using the User class in the previous article as an example, let's create a User object:
Copy codeThe Code is as follows:
>>> Ed_user = User ('ed', 'ed Jones ', 'edspassword ')
>>> Ed_user.name
'Ed'
>>> Ed_user.password
'Edspassword'
>>> Str (ed_user.id)
'None'
It is instantiated like a common Python class. You may ask why ed_user.id is a None value. First, the id attribute is not initialized through the _ init _ () constructor, therefore, by default, the id Column (Column) of the previously defined ORM will generate a None value. By default, the orm will create class attributes for all ing columns, these attributes are implemented through the Descriptors mechanism in the Python language. Therefore, the use of these attributes includes some additional behaviors, including tracking and modification, or automatically loading new data from the database when necessary, that is, when we use these attributes, both modification and reading will trigger a series of actions inside the ORM.


Wait, you have not explained why the property id is None. In fact, we have not inserted data into the database. Generally, the primary key property will automatically generate a non-repeated value during database insertion to ensure uniqueness. Since we have not implemented Persist for the object (the so-called persistence is to store the object data into the database according to the ing relationship), the id value here is None. Don't worry. When we talk about data persistence later, you can see a new automatically generated id.

Next, let's talk about the lazy trick :-)

If we do not define the constructor _ init _ () of the ing Class, will it have any adverse effects? No. SQLAlchemy considers this for us. If we are lazy, we define the previous User class as follows:
Copy codeThe Code is 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 the Base (see the previous article for the definition of the Base), the Declarative system manages the User. The Declarative system finds that this class lacks the constructor method, so we were very friendly to add a constructor. Of course, the constructor provided by the constructor cannot use location-based parameter access as we defined the constructor, we recommend that you use key-based parameter access, including all columns that use Column to define ing. For example:
Copy codeThe Code is as follows:
U1 = User (name = 'ed', fullname = 'ed Jones ', password = 'foobar ')
Id can also be passed in. Generally, this type of primary key is automatically maintained by the system, and we do not need to assign a value to it.

2. Create and use sessions)

Here it can be said that "everything is ready and everything is in trouble ", in the official document, "We are now ready to talk to the database" (We're re now ready to start talking to the database ). An ORM Handle is called a Session ). To use a Session, we need to configure it first. The Code statement for configuring the Session should be at the same code level (put together) as the Code statement for create_engine () engine creation engine ).

For example, we use create_engine () to first set up the engine name as engine (for the engine creation code, refer to my first article), and then use the sessionmaker () factory function to create a Session class, bind our existing engine at the same time. For example, the Code is as follows:
Copy codeThe Code is as follows:
>>> From sqlalchemy. orm import sessionmaker
>>> Session = sessionmaker (bind = engine)
If the code for creating a Session is not at the same level as the code for creating an engine, for example, sessionmaker () is a Session class before create_engine () is used to create an engine, so we still have the opportunity to bind the Session and the engine together? Of course, we can use the configure method of the Session class to configure engine binding, for example:
Copy codeThe Code is as follows:
Session = sessionmaker ()
# Engine = create_engine (...) Create an engine
Session. configure (bind = engine) # Here the engine should have been created
The Session class created through the sessionmaker () factory should be bound to the previously created Engine, but the Session has not actually started yet. To start the Session, we need to instantiate this Session class:
Copy codeThe Code is as follows:
>>> Session = Session ()
Here, the session gets the database connection pool maintained by the Engine, and maintains the ing data in the memory until the commit Changes or closes the session object.

The session creation here is complete. Next we will explain the real ORM database query section. Welcome to the 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.