Home Backend Development Python Tutorial Solving the problem of Django database connection loss (explanation with examples)

Solving the problem of Django database connection loss (explanation with examples)

Dec 29, 2018 am 10:35 AM
django mysql python

The content of this article is about solving the problem of Django database connection loss (explanation with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Problem

When using mysql in Django, the database connection may occasionally be lost. The errors usually include the following two types

1. `OperationalError: (2006, 'MySQL server has gone away')`  
1. `OperationalError: (2013, 'Lost connection to MySQL server during query')`
Copy after login

Query mysql global variables SHOW GLOBAL VARIABLES ;You can see wait_timeout, this variable represents the connection idle time. If the client uses one connection to query the database multiple times, there will be no problem if the query is continuous. If the query pauses for more than wait_timeout after several queries, the database connection will be lost and the database connection will be lost.

Reproduction

Use Django to reproduce the problem next time:

1. Set the wait_timeout of mysql to 10 seconds, and then enter the django shell simulation Query (only part of the following error message is retained)

In[1]:import time
In[2]:from django.contrib.auth.models import User
In[3]:list(User.objects.filter(id=1))
Out[3]:[<User: admin>]
In[4]:time.sleep(15) # 模拟比较慢的代码(其中没有查询数据库的代码),或者空闲什么都不操作一段时间,此时间要比`wait_timeout`大一些
list(User.objects.filter(id=1))
Traceback (most recent call last):
  File "<ipython-input-4-3574ae8220ee>", line 1, in <module>
    list(User.objects.filter(id=1))

  File "/usr/lib/python3.6/site-packages/pymysql/connections.py", line 1037, in _read_bytes
    CR.CR_SERVER_LOST, "Lost connection to MySQL server during query")
django.db.utils.OperationalError: (2013, 'Lost connection to MySQL server during query')
Copy after login

Seeking

Then the above problem basically shows that the error is caused by too long idle time.
In order to reduce unnecessary database connections and closures, Django reuses database connections. When a request is started, a connection pool is established to store the connection. After that, a connection is reused for each request. My guess is that Django saves the connection longer than wait_timeout. If the save time is shorter, the connection can be re-established to avoid this error.
Yes, the official document has also explained this problem, setting the database CONN_MAX_AGE parameter, example:

DATABASES = {
    "default": {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': '',
            'USER': '',
            'PASSWORD': '',
            'HOST': '',
            'CONN_MAX_AGE': 9  # 比wait_timeout小一些
    }
}
Copy after login

When we tested it, we found that things were not as simple as we thought. Why does the error still occur? Behind all this, is it the distortion of human nature or the loss of morality? Please watch the next episode "Breakthrough".

Breakthrough

After searching CONN_MAX_AGE in the django source code, I followed the clues and found out how django closes the failed connectiondjango. db.close_old_connections()

# Register an event to reset transaction state and close connections past
# their lifetime.
def close_old_connections(**kwargs):
    for conn in connections.all():
        conn.close_if_unusable_or_obsolete()

signals.request_started.connect(close_old_connections)
signals.request_finished.connect(close_old_connections)
Copy after login

The focus is on the last two lines. This method is executed when specific events are implemented through signal. The two specific events, as the name implies, are the start of the request and the end of the request. The error we reported was in one request, so this method is usually ineffective. It only closes and re-establishes the connection for each request.

Solution

Do not close the django shell that reproduces the problem. Continue to execute the following code:

In[5]:from django.db import close_old_connections
In[6]:close_old_connections()
In[7]:list(User.objects.filter(id=1))
Out[7]: [<User: admin>]
Copy after login

Call django.db.close_old_connections and query again. No more errors.
Then if we want to avoid this error, we must call the django.db.close_old_connections method before executing each database query.

1. Generally, this kind of problem will not occur, because the database query is continuously performed in one request, and there is no need to call this method for every request. This is a groundless worry.

2. Sometimes there is a large amount of data in a request, and the database will be queried and then other processing (not involving the database) will be performed for a period of time. For example, some data will be queried first, then the data will be processed, excel will be generated, the file will be saved, and Generate url. It is known that this takes a very long time, so it is best to call django.db.close_old_connections first to prevent the connection from being lost when the final URL is saved in the database.

The above is the detailed content of Solving the problem of Django database connection loss (explanation with examples). 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)

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Does Python projects need to be layered? Does Python projects need to be layered? Apr 19, 2025 pm 10:06 PM

Discussion on Hierarchical Structure in Python Projects In the process of learning Python, many beginners will come into contact with some open source projects, especially projects using the Django framework...

How to safely store JavaScript objects containing functions and regular expressions to a database and restore? How to safely store JavaScript objects containing functions and regular expressions to a database and restore? Apr 19, 2025 pm 11:09 PM

Safely handle functions and regular expressions in JSON In front-end development, JavaScript is often required...

See all articles