当前位置:  开发笔记 > 编程语言 > 正文

Flask/Apache中的PyMySQL有时返回空结果

如何解决《Flask/Apache中的PyMySQL有时返回空结果》经验,为你挑选了0个好方法。

我有一个Flask应用程序,在Apache中运行,依赖于PyMySQL.该应用程序提供了一系列REST命令.它在Python 3下运行.

在不提供整个来源的情况下,该计划的结构如下:

#!flask/bin/python
import json
import pymysql
from flask import *

# Used to hopefully share the connection if the process isn't restarted
mysql_connection = None   

# Gets the mysql_connection, or opens it
GetStoreCnx():
    global mysql_connection
    if (mysql_connection != None):
        store_connection_string = ""
        # Get the connection string from the config file
        with open('config/storedb.json', 'r') as f:
            store_connection_string = json.load(f)
        mysql_connection = pymysql.connect(**store_connection_string)
    return mysql_connection;


class Server(Flask):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

# Return results via REST
@app.route('/results1', methods=['GET'])
def get_result1():
    cnx = GetStoreCnx();
    cursor = cnx.cursor();
    query = """
        SELECT 
            result_name,
            successful
        FROM
            results
        """
    cursor.execute(query)
    cnx.commit()
    result = cursor.fetchall()
    return json.dumps(result)

# Run server, if needed
if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)

还有一些REST调用 - 但它们基本上都做同样的事情(即 - 获取连接,创建游标,运行基本选择查询 - 有时会有超过2个字段,执行查询,获取结果和将其作为JSON对象返回).那里的提交应该是不必要的,但它似乎是PyMySQL的一个运行问题导致获取旧数据.

问题是这些REST调用有时会返回空的JSON集(即.[]).进一步的调查表明,执行调用有时会返回一个完全空的结果,但不会抛出异常.这种情况经常发生 - 但并非始终如此.有些调用会成功返回值.当我尝试保持呼叫进行直到它返回结果(如:

while(cursor.execute(query) < 1):
    pass

)进程进入无限循环,最终(快速)阻止apache为更多请求提供服务.

服务器(目前)仅每秒服务大约5个呼叫.如果我使用开发服务器,则不会出现此问题.

有什么办法可以防止这个错误吗?这是PyMySQL的错吗?我正在做的事情阻止与MySQL的正确连接?

推荐阅读
赛亚兔备_393
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有