【问题标题】:modwsgi and mysql. queries only show actual result after touched wsgi filemodwsgi 和 mysql。查询仅在触摸 wsgi 文件后显示实际结果
【发布时间】:2023-03-15 23:29:01
【问题描述】:

我对 modwsgi 和 mysql 有疑问。我有一个非常简单的 wsgi 应用程序:

import MySQLdb
conn_mysql = MySQLdb.connect('localhost', 'root', 'asd', 'testwsgi')

def application(environ, start_response):
    status='200 OK'
    start_response(status, [('Content-Type', 'text/html; charset=utf-8')])
    result = getTheResult()
    return result

def getTheResult():
    returnStr = ""
    cursor_mysql = conn_mysql.cursor()
    cursor_mysql.execute("SELECT * FROM test1")

    for row in cursor_mysql:
        returnStr = returnStr + row[1] + " " + row[2] + "<br>"
    cursor_mysql.close()
    return returnStr

每当我在 mysql 数据库中进行更改时,结果不会反映它,直到我触摸 wsgi 文件。我在守护进程模式下运行 wsgi。

我找到了这篇文章,我想我会按照建议去做:

WSGI ( is caching mysql result until script code is modified ) code included. ( want to stop this caching )

我确定我必须忽略一些非常容易的事情。非常感谢您的帮助。

【问题讨论】:

  • 不太可能是您的问题的原因,但此代码不一定是线程安全的,这将是一个问题,因为 mod_wsgi 守护程序模式默认是多线程的。您应该为每个请求创建连接,而不是在模块导入时全局创建一次。
  • 感谢@GrahamDumpleton 的回复。这实际上解决了我的问题。我将 conn_mysql = MySQLdb.connect('localhost', 'root', 'asd', 'testwsgi') 移到 getTheResult() 函数中。这是否意味着如果我在全局范围内声明某些内容,它只会加载一次?即使是导入的模块?
  • 如果在模块的全局范围内,它只会被执行一次。这将在导入模块时发生。
  • @GrahamDumpleton 非常感谢。这帮助很大。

标签: python mysql mod-wsgi wsgi mysql-python


【解决方案1】:

我的问题通过在 getTheResult() 函数中移动到 mysql 数据库的连接得到解决。

import MySQLdb

def application(environ, start_response):
    status='200 OK'
    start_response(status, [('Content-Type', 'text/html; charset=utf-8')])
    result = getTheResult()
    return result

def getTheResult():
    conn_mysql = MySQLdb.connect('localhost', 'root', 'asd', 'testwsgi')
    returnStr = ""
    cursor_mysql = conn_mysql.cursor()
    cursor_mysql.execute("SELECT * FROM test1")

    for row in cursor_mysql:
        returnStr = returnStr + row[1] + " " + row[2] + "<br>"
    cursor_mysql.close()
    return returnStr

【讨论】:

    猜你喜欢
    • 2015-03-29
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-27
    • 2012-06-04
    • 2014-09-04
    相关资源
    最近更新 更多