Table of Contents
Background
Initialization work
Personal design
Mapping statement (Model introduction)
Session introduction
Home Backend Development Python Tutorial A magic tool for newbies to learn Python and play with SQL in five minutes!

A magic tool for newbies to learn Python and play with SQL in five minutes!

Apr 12, 2023 pm 05:28 PM
python sql

A magic tool for newbies to learn Python and play with SQL in five minutes!

Background

In fact, I used pymysql at the beginning, but found that maintenance was troublesome and there was a risk of code injection, so I simply used the ORM framework directly.

ORM is Object Relational Mapper, which can be simply understood as the mapping between database tables and Python classes. By operating Python classes, you can indirectly operate the database.

The more famous Python ORM frameworks are SQLAlchemy and Peewee. I will not make a comparison here, but simply explain some of my personal use of SQLAlchemy. I hope it can be helpful to all my friends.

  • sqlalchemy version: 1.3.15
  • pymysql version: 0.9.3
  • mysql version: 5.7

Initialization work

Generally, when using an ORM framework, there will be some initialization work, such as database connection, defining basic mapping, etc.

Take MySQL as an example. To create a database connection, you only need to pass in the DSN string. Echo indicates whether to output the corresponding SQL statement, which is helpful for debugging.

from sqlalchemy import create_engine
engine = create_engine('mysql+pymysql://$user:$password@$host:$port/$db?charset=utf8mb4', echo=True)
Copy after login

Personal design

For me personally, when introducing the ORM framework, my project will refer to the MVC pattern for the following design. Among them, model stores some database models, that is, Python classes mapped to database tables; model_op stores the operations corresponding to each model, that is, adding, deleting, checking, and modifying; when the caller (such as main.py) performs database operations, it only needs to call model_op layer, you don’t need to care about the model layer to achieve decoupling.

├── main.py
├── model
│ ├── __init__.py
│ ├── base_model.py
│ ├── ddl.sql
│ └── py_orm_model.py
└── model_op
 ├── __init__.py
 └── py_orm_model_op.py
Copy after login

Mapping statement (Model introduction)

For example, if we have such a test table

create table py_orm (
 `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '唯一id',
 `name` varchar(255) NOT NULL DEFAULT '' COMMENT '名称',
 `attr` JSON NOT NULL COMMENT '属性',
 `ct` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
 `ut` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON update CURRENT_TIMESTAMP COMMENT '更新时间',
 PRIMARY KEY(`id`)
)ENGINE=InnoDB COMMENT '测试表';
Copy after login

In the ORM framework, the mapping result is the Python below Class

# py_orm_model.py
from .base_model import Base
from sqlalchemy import Column, Integer, String, TIMESTAMP, text, JSON
class PyOrmModel(Base):
 __tablename__ = 'py_orm'
 id = Column(Integer, autoincrement=True, primary_key=True, comment='唯一id')
 name = Column(String(255), nullable=False, default='', comment='名称')
 attr = Column(JSON, nullable=False, comment='属性')
 ct = Column(TIMESTAMP, nullable=False, server_default=text('CURRENT_TIMESTAMP'), comment='创建时间')
 ut = Column(TIMESTAMP, nullable=False, server_default=text('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), comment='更新时间')
Copy after login

First, we can see that PyOrmModel inherits the Base class, which is a base class provided by sqlalchemy. It will do some checks on the Python class we declared, and I put it in base_model.

# base_model.py
# 一般base_model做的都是一些初始化的工作
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:33306/orm_test?charset=utf8mb4", echo=False)
Copy after login

Secondly, each Python class must contain the __tablename__ attribute, otherwise the corresponding table cannot be found.

Third, there are two ways to create a data table. The first is of course to create it manually in MySQL. As long as there is no problem with your Python class definition, it can operate normally; the second is to use ORM Framework creation, such as the following:

# main.py
# 注意这里的导入路径,Base创建表时会寻找继承它的子类,如果路径不对,则无法创建成功
from sqlachlemy_lab import Base, engine
if __name__ == '__main__':
 Base.metadata.create_all(engine)
Copy after login

Creation effect:

...
2020-04-04 10:12:53,974 INFO sqlalchemy.engine.base.Engine
CREATE TABLE py_orm (
id INTEGER NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL DEFAULT '' COMMENT '名称',
attr JSON NOT NULL COMMENT '属性',
ct TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
ut TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 PRIMARY KEY (id)
)
Copy after login

Fourth, about field attributes

  • 1.primary_key and autoincrement are easier to understand, they are MySQL’s Primary keys and incremental attributes.
  • 2. If it is an int type, you do not need to specify the length, but if it is a varchar type, you must specify it.
  • 3.nullable corresponds to NULL and NOT NULL in MySQL
  • 4. About default and server_default: default represents the default value at the ORM framework level, that is, if the field is inserted when inserting If no value is assigned, the default value we defined will be used; server_default represents the default value at the database level, which is the default keyword in the DDL statement.

Session introduction

It is mentioned in the SQLAlchemy documentation that additions, deletions, and modifications to the database are performed through sessions.

>>> from sqlalchemy.orm import sessionmaker
>>> Session = sessionmaker(bind=engine)
>>> session = Session()
>>> orm = PyOrmModel(id=1, name='test', attr={})
>>> session.add(orm)
>>> session.commit()
>>> session.close()
Copy after login

As above, we can see that for each operation, we need to acquire, submit and release the session. This is too redundant and troublesome, so we usually perform a layer of encapsulation.

1. Use the context manager to handle abnormal rollback and closure of the session. This part is almost consistent with the referenced article.

# base_model.py
from contextlib import contextmanager
from sqlalchemy.orm import sessionmaker, scoped_session
def _get_session():
 """获取session"""
 return scoped_session(sessionmaker(bind=engine, expire_on_commit=False))()
# 在这里对session进行统一管理,包括获取,提交,回滚和关闭
@contextmanager
def db_session(commit=True):
 session = _get_session()
 try:
 yield session
 if commit:
 session.commit()
 except Exception as e:
 session.rollback()
 raise e
 finally:
 if session:
 session.close()
Copy after login

2. Add two methods in PyOrmModel for conversion between model and dict

class PyOrmModel(Base):
 ...
 @staticmethod
 def fields():
 return ['id', 'name', 'attr']
 @staticmethod
 def to_json(model):
 fields = PyOrmModel.fields()
 json_data = {}
 for field in fields:
 json_data[field] = model.__getattribute__(field)
 return json_data
 @staticmethod
 def from_json(data: dict):
 fields = PyOrmModel.fields()
 model = PyOrmModel()
 for field in fields:
 if field in data:
 model.__setattr__(field, data[field])
 return model
Copy after login

3. Encapsulation of database operations, different from the reference article, I call it directly The session is removed, so that the caller does not need to pay attention to the model layer and reduces coupling.

# py_orm_model_op.py
from sqlachlemy_lab.model import db_session
from sqlachlemy_lab.model import PyOrmModel
class PyOrmModelOp:
 def __init__(self):
 pass
 @staticmethod
 def save_data(data: dict):
 with db_session() as session:
 model = PyOrmModel.from_json(data)
 session.add(model)
 # 查询操作,不需要commit
 @staticmethod
 def query_data(pid: int):
 data_list = []
 with db_session(commit=False) as session:
 data = session.query(PyOrmModel).filter(PyOrmModel.id == pid)
 for d in data:
 data_list.append(PyOrmModel.to_json(d))
 return data_list
Copy after login

4. Caller

# main.py
from sqlachlemy_lab.model_op import PyOrmModelOp
if __name__ == '__main__':
 PyOrmModelOp.save_data({'id': 1, 'name': 'test', 'attr': {}})
Copy after login

For complete code, please see:

​https://github.com/yangancode/python_lab/tree/master/ sqlachlemy_lab​

The above is the detailed content of A magic tool for newbies to learn Python and play with SQL in five minutes!. 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)

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Golang vs. Python: Concurrency and Multithreading Golang vs. Python: Concurrency and Multithreading Apr 17, 2025 am 12:20 AM

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

See all articles