简体   繁体   English

在 Python 中使用 PyMysql 连接 MariaDB 时出现问题

[英]Problem connecting MariaDB using PyMysql in Python

I have a Flask Python API that connects with a MariaDB database in a Docker container and I'm connecting to the database with PyMysql .我有一个 Flask Python API,它与Docker 容器中的 MariaDB 数据库连接,我正在使用PyMysql连接到数据库。

The problem is that my server or application closes the connection after 10 minutes.问题是我的服务器或应用程序在 10 分钟后关闭了连接。 I've already tried to increase the timeout time in the MariaDB configuration file and in PyMySQL, but to no avail.我已经尝试在 MariaDB 配置文件和 PyMySQL 中增加超时时间,但无济于事。 The errors are as follows:错误如下:

Python error:蟒蛇错误:

"OperationalError: (2006, "MySQL server has gone away 
(ConnectionResetError(104, 'Connection reset by peer'))")"

Database error:数据库错误:

"[Warning] Aborted connection 9 to db: 'db' user: 'user' host: 'ip'
(Got timeout reading communication packets)"

Would anyone know how to solve the problem?有人知道如何解决这个问题吗?

I give below my MariaDB configuration file and my Python code.我在下面给出了我的 MariaDB 配置文件和我的 Python 代码。

Thank you in advance.先感谢您。

PS: I've already tried to use another Python package to connect to MariaDB, that is through the Flask SQLAlchemy, but the same behavior happens with the database connection, unfortunately. PS:我已经尝试使用另一个 Python 包连接到 MariaDB,即通过 Flask SQLAlchemy,但不幸的是,同样的行为发生在数据库连接上。 For that reason, I believe that the problem is not the Python code, but maybe the Docker image (maybe).出于这个原因,我认为问题不在于 Python 代码,而在于 Docker 映像(也许)。

my.cnf我的.cnf

# 7 days = 604800s / 8 hours = 28800s 
wait_timeout = 604800
interactive_timeout = 28800

Python code:蟒蛇代码:

from pymysql import connect
from pymysql.cursors import DictCursor


class MySQLConnection:

    def __init__(self, host, port, user, password, schema):       
        try:
            # Connect to the database
            self.connection = connect(host=host, port=port, 
                                      user=user, password=password, 
                                      db=schema, cursorclass=DictCursor, 
                                      connect_timeout=50)

            # create a cursor object
            self.cursor = self.connection.cursor()
            print("DB connection was successful!")
        except Exception as error:
            print("DB connection was failed! \nError: ", error)
            exit(1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM