Home Backend Development Python Tutorial ORM framework Databases in Python in practice

ORM framework Databases in Python in practice

Jun 10, 2023 pm 05:42 PM
Actual combat orm databases

In recent years, Python has become an efficient, easy-to-use, and flexible programming language, and in the field of Python development, the application of Databases ORM framework is becoming more and more common. Databases is a simple, intuitive, lightweight ORM framework that supports a variety of databases, including but not limited to MySQL, PostgreSQL, SQLite and Microsoft SQL Server. This article will introduce you to the Databases framework in detail and its specific application in Python development.

1. The concept of ORM framework

ORM stands for Object Relational Mapping, which is a mapping between relational database tables and Python objects, thereby enabling developers to The technology of operating SQL statements is no longer needed in the programming process. The application of the ORM framework in Python provides developers with more choices and makes program development more convenient.

2. Databases framework

Databases is a simple ORM framework developed by Django ORM developer Andrew Goodwin. Its biggest feature is that it is lightweight, convenient and easy to use. It also supports a variety of databases, including MySQL, PostgreSQL, SQLite and Microsoft SQL Server.

  1. Install the Databases framework

For the installation of the Databases framework, you can use pip to install it. The command is as follows:

pip install databases==0.4.*
Copy after login
  1. Connect to the database

Before using the Databases framework for development, you need to connect to the database first. The parameters required to connect to the database include database type, host name, database name, user name and password, etc. In this development, we try to connect to the MySQL database. The code is as follows:

import databases

DATABASE_URL = "mysql://user:password@hostname/database_name"

database = databases.Database(DATABASE_URL)
Copy after login
Copy after login

Here, QAQsaaspassword is the password to connect to the database, askdnsadn312as is the username to connect to the database, and localhost is the host name or IP address where the database is located. , my_database is the name of the database.

  1. Create tables and columns

The Databases framework supports SQL expression language to create complex query statements, allowing developers to more flexibly control the SQL execution process. In the Databases framework, we can use the Table class to create tables and the Column class to create columns.

The table creation code is as follows:

import sqlalchemy

metadata = sqlalchemy.MetaData()

users = sqlalchemy.Table(
    "users",
    metadata,
    sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True),
    sqlalchemy.Column("username", sqlalchemy.String),
    sqlalchemy.Column("password", sqlalchemy.String),
    sqlalchemy.Column("email", sqlalchemy.String),
)
Copy after login

Here, we use the MetaData object in SQLAlchemy and create four fields (id, username, password and email) by defining a users table.

  1. Execute SQL statements

The Databases framework also provides a method of directly using SQL statements for operations, which is more flexible. SQL statements can be executed through the execute() method. The code is as follows:

result = await database.execute(query)
Copy after login

query represents the SQL statement code, and result is the execution result. When the execution is successful, it will return a dict type Composed of a list, each dict represents a record in the SQL query result.

5. Use ORM in Databases

The Databases framework also supports ORM to operate SQL statements, which is more convenient for developers. The ORM method helps map object relationships to the database, making the code more readable and maintainable.

Using ORM, we can operate the database by defining a model. The code is as follows:

import sqlalchemy

metadata = sqlalchemy.MetaData()

users = sqlalchemy.Table(
    "users",
    metadata,
    sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True),
    sqlalchemy.Column("username", sqlalchemy.String),
    sqlalchemy.Column("password", sqlalchemy.String),
    sqlalchemy.Column("email", sqlalchemy.String),
)

class UserModel:
    id: int
    username: str
    password: str
    email: str

    __tablename__ = "users"

    query: sq.Select

    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)
Copy after login

Here, we define a UserModel model class to represent our data table object. At the same time Through simple definitions, we can complete the definition of tables and columns in SQLAlchemy, so that its ORM can be mapped to the database, which is convenient, fast, and easy to maintain.

3. Application Example

Here, we take a simple blog application as an example to demonstrate the specific operation of the Databases framework.

1. Connect to the database

The information required to connect to the database is also very simple, as shown in the following code:

import databases

DATABASE_URL = "mysql://user:password@hostname/database_name"

database = databases.Database(DATABASE_URL)
Copy after login
Copy after login

The DATABASE_URL here specifies the connection to MySQL. parameters to connect to our database system.

2. Define the model

In this blog example, we need to define two data models. One is the Blog model, which represents the blog post object. The generated code is as follows:

class Blog:
    id: int
    title: str
    description: str
    content: str

    __tablename__ = "blog"

    query: sq.Select

    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)
Copy after login

The other is the User model, which represents the user object. The generated code is as follows:

class User:
    id: int
    name: str
    email: str
    password: str

    __tablename__ = "user"

    query: sq.Select

    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)
Copy after login

Similarly, we use a simple definition to map its ORM to the MySQL database we connect to.

3. Create a table

Since the database system we operate is MySQL, we need to create the corresponding table. The generated code is as follows:

CREATE TABLE `blog` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(100) DEFAULT NULL,
  `description` varchar(100) DEFAULT NULL,
  `content` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `user` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  `email` varchar(100) DEFAULT NULL,
  `password` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Copy after login

4. Insert data

We can use ORM to input data very conveniently. The generated code is as follows:

async def create_blog_post(title: str, description: str, content: str):
    query = blog.insert().values(title=title, description=description, content=content)
    return await database.execute(query)

async def create_user(name: str, email: str, password: str):
    query = user.insert().values(name=name, email=email, password=password)
    return await database.execute(query)
Copy after login

Here we use the insert() method to complete the data insertion operation, which is very readable. , to facilitate developers to better maintain code.

5. Query data

The Databases framework also supports query operations, as shown in the following code:

async def get_blog_post(id: int):
    query = blog.select().where(blog.c.id == id)
    return await database.fetch_one(query)

async def get_all_users():
    query = user.select()
    return await database.fetch_all(query)

async def get_users_by_email(email: str):
    query = user.select().where(user.c.email == email)
    return await database.fetch_all(query)
Copy after login

Here we use the select() method to splice the conditions to obtain a generated A device that returns a number of pairs when traversing. We can also filter and sort data by using query data.

Summarize

Databases framework is a flexible, easy-to-use, lightweight ORM framework for Python developers. It can easily support a variety of databases and facilitate developers to store, operate, filter and sort data, etc. . This article demonstrates the flexibility and ease of use of the Databases framework from connecting to the database to defining model operations, to data insertion and query operations, making it easier for developers to develop Python programs more efficiently.

The above is the detailed content of ORM framework Databases in Python in practice. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use object-relational mapping (ORM) in PHP to simplify database operations? How to use object-relational mapping (ORM) in PHP to simplify database operations? May 07, 2024 am 08:39 AM

Database operations in PHP are simplified using ORM, which maps objects into relational databases. EloquentORM in Laravel allows you to interact with the database using object-oriented syntax. You can use ORM by defining model classes, using Eloquent methods, or building a blog system in practice.

PHP Practical: Code Example to Quickly Implement Fibonacci Sequence PHP Practical: Code Example to Quickly Implement Fibonacci Sequence Mar 20, 2024 pm 02:24 PM

PHP Practice: Code Example to Quickly Implement the Fibonacci Sequence The Fibonacci Sequence is a very interesting and common sequence in mathematics. It is defined as follows: the first and second numbers are 0 and 1, and from the third Starting with numbers, each number is the sum of the previous two numbers. The first few numbers in the Fibonacci sequence are 0,1,1.2,3,5,8,13,21,...and so on. In PHP, we can generate the Fibonacci sequence through recursion and iteration. Below we will show these two

How does Hibernate implement polymorphic mapping? How does Hibernate implement polymorphic mapping? Apr 17, 2024 pm 12:09 PM

Hibernate polymorphic mapping can map inherited classes to the database and provides the following mapping types: joined-subclass: Create a separate table for the subclass, including all columns of the parent class. table-per-class: Create a separate table for subclasses, containing only subclass-specific columns. union-subclass: similar to joined-subclass, but the parent class table unions all subclass columns.

What is the ORM mechanism of Java Hibernate framework? What is the ORM mechanism of Java Hibernate framework? Apr 17, 2024 pm 02:39 PM

Hibernate is a JavaORM framework for mapping between Java objects and relational databases. Its ORM mechanism includes the following steps: Annotation/Configuration: The object class is marked with annotations or XML files, specifying its mapped database tables and columns. Session factory: manages the connection between Hibernate and the database. Session: Represents an active connection to the database and is used to perform query and update operations. Persistence: Save data to the database through the save() or update() method. Query: Use Criteria and HQL to define complex queries to retrieve data.

Java development practice: Integrating Qiniu cloud storage service to achieve file upload Java development practice: Integrating Qiniu cloud storage service to achieve file upload Jul 06, 2023 pm 06:22 PM

Java Development Practice: Integrating Qiniu Cloud Storage Service to Implement File Upload Introduction With the development of cloud computing and cloud storage, more and more applications need to upload files to the cloud for storage and management. The advantages of cloud storage services are high reliability, scalability and flexibility. This article will introduce how to use Java language development, integrate Qiniu cloud storage service, and implement file upload function. About Qiniu Cloud Qiniu Cloud is a leading cloud storage service provider in China, providing comprehensive cloud storage and content distribution services. Users can use Qiniu Yunti

What are the disadvantages of Hibernate ORM framework? What are the disadvantages of Hibernate ORM framework? Apr 18, 2024 am 08:30 AM

The HibernateORM framework has the following shortcomings: 1. Large memory consumption because it caches query results and entity objects; 2. High complexity, requiring in-depth understanding of the architecture and configuration; 3. Delayed loading delays, leading to unexpected delays; 4. Performance bottlenecks, in May occur when a large number of entities are loaded or updated at the same time; 5. Vendor-specific implementation, resulting in differences between databases.

How PHP object-relational mapping and database abstraction layers improve code readability How PHP object-relational mapping and database abstraction layers improve code readability May 06, 2024 pm 06:06 PM

Answer: ORM (Object Relational Mapping) and DAL (Database Abstraction Layer) improve code readability by abstracting the underlying database implementation details. Detailed description: ORM uses an object-oriented approach to interact with the database, bringing the code closer to the application logic. DAL provides a common interface that is independent of database vendors, simplifying interaction with different databases. Using ORM and DAL can reduce the use of SQL statements and make the code more concise. In practical cases, ORM and DAL can simplify the query of product information and improve code readability.

In-depth study of Elasticsearch query syntax and practical combat In-depth study of Elasticsearch query syntax and practical combat Oct 03, 2023 am 08:42 AM

In-depth study of Elasticsearch query syntax and practical introduction: Elasticsearch is an open source search engine based on Lucene. It is mainly used for distributed search and analysis. It is widely used in full-text search of large-scale data, log analysis, recommendation systems and other scenarios. When using Elasticsearch for data query, flexible use of query syntax is the key to improving query efficiency. This article will delve into the Elasticsearch query syntax and give it based on actual cases.

See all articles