【问题标题】:Weird concurrency issue with Flask (flask-restful) and MySQLdb (PyMySQL)Flask (flask-restful) 和 MySQLdb (PyMySQL) 的奇怪并发问题
【发布时间】:2021-09-19 22:26:35
【问题描述】:

我有一个使用 MySQL 数据库的 flask-restful 项目,我目前正在使用 PyMysql 连接到数据库,我之前尝试使用 flask-mysqldb 和 flask-mysql 但它们并没有真正奏效,因为我需要在请求方法外部使用db连接(主要用于装饰器),所以我开始使用PyMySQL,但现在我发现并发问题,每当我尝试同时发出超过2个并发请求时时间(这意味着 2 个并发查询)我收到此错误:

mysqldb._exceptions.programmingerror: (2014, "commands out of sync; you can't run this command now")

事实上,我确实在每次查询后调用cursor.nextset 以确保结果被完全使用,并且我确实确保我的所有查询和存储过程都是正确的并且没有任何问题,我开始认为问题是由服务器仅使用一个游标引起的,因为游标是在一个单独的模块中定义的,所有视图/资源都将其导入以完成工作(它们不会创建新游标),但是在我创建每个视图/资源方法之后一个新的光标可以使用并在之后关闭它,我仍然遇到同样的错误。 这就是我执行查询的方式:

cursor.callproc('do_something', (arg1, arg2))
result = cursor.fetch_all()
cursor.nextset()

它也与竞争条件无关,因为查询不写任何东西。我尝试通过 Waitress 为应用程序提供服务,但我仍然遇到问题。

【问题讨论】:

    标签: python mysql flask flask-restful pymysql


    【解决方案1】:

    对于 MySQLdb 存储过程

    cursor.callproc('do_something', (arg1, arg2))
    

    这里你必须为所有输出参数添加一个变量

    cursor.execute('SELECT @outparameter1, @outparameter2, @outparameter3')
    
    cursor.fetchall()
    

    对于 pymyslq,您需要进行更多更改,因为没有 callproc

    cusrorType      = pymysql.cursors.DictCursor
    
     
    
    databaseConnection   = pymysql.connect(host=hostName,
    
                                           user=userName,
    
                                           password=userPassword,
    
                                           db=databaseName,
    
                                           charset=databaseCharset,
    
                                           cursorclass=cusrorType)
    
                                        
    
    try:
    
        # Cursor object creation
    
        cursorObject    = databaseConnection.cursor()                                    
    
     
    
        # Execute the sqlQuery
    
        cursorObject.execute("call do_something(?,?)",arg1, arg2)
    
     
    
        # Print the result of the executed stored procedure
    
        for result in cursorObject.fetchall():
    
            print(result)
    

    对于 mysq.connector 您必须事先调用`store_result,例如

    cursor.callproc('do_something', (arg1, arg2))
    for result in cursor.stored_results():
        result.fetchall()
    

    【讨论】:

    • 这不起作用,我收到此错误:AttributeError: 'DictCursor' object has no attribute 'stored_results'
    • 你说得对,这只适用于 mysql connerctor
    • @InfinityVive 我为 pymysql 添加了代码 no callproc
    • 啊,对不起,我使用的是 MySQLdb,而不是 PyMysql,虽然它们是相同的,但根据你所说的可能它们是不同的
    • 那更复杂,因为我不知道你的存储过程,所以看例子
    猜你喜欢
    • 2014-11-04
    • 2019-02-15
    • 1970-01-01
    • 2013-10-25
    • 1970-01-01
    • 2021-06-25
    • 2019-05-11
    • 1970-01-01
    • 2020-04-27
    相关资源
    最近更新 更多