【问题标题】:How to place WSGI script mysql query into a ' function '如何将 WSGI 脚本 mysql 查询放入“函数”
【发布时间】:2014-05-27 16:16:32
【问题描述】:

因为我是新人,也因为在谷歌搜索 WSGI 时没有太多工作可做。我需要弄清楚如何将下面的 mysql 查询放入 WSGI 脚本中的函数中。

这是当前的非功能版本。

import MySQLdb
conn = MySQLdb.connect (host = "localhost",
                        user = "a",
                        passwd = "",
                        db = "a")
cursor = conn.cursor ()
cursor.execute ("select * from `01` where id in (1) limit 1")
rows = cursor.fetchall()
cursor.close ()
conn.close ()

aaa = rows[0][1]

def application(environ, start_response):
    start_response('200 OK', [('content-type', 'text/html')])
    yield aaa

只需让我知道如何将该 mysql 查询放入一个函数中,然后从一个函数中调用它。我知道如何在 PHP 中使用函数,但在 WSGI 方面没有太多经验

【问题讨论】:

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


    【解决方案1】:

    设置代码应该运行一次,而不是针对每个查询,以便保持在顶部:

    import MySQLdb
    conn = MySQLdb.connect(
        host   = "localhost",
        db     = "a"
        user   = "a",
        passwd = "",
    )
    

    查询特定代码进入def 并获得一个名称:

    def query():
        cursor = conn.cursor()
    
        cursor.execute("select * from `01` where id in (1) limit 1")
        rows = cursor.fetchall()
        cursor.close ()
    
        return rows
    

    清理代码,如启动代码,运行一次 -- 但在最后:

    conn.close()
    

    函数的调用方式如下:

    results = query()
    

    【讨论】:

    • 如果 WSGI 应用程序部署在多线程 WSGI 服务器上,则连接的创建不能在模块的全局范围内。这是因为并发请求会争夺同一连接的使用。
    • @GrahamDumpleton 所以创建一个返回当前线程连接的方法(创建它或使用缓存版本)。然后 query() 可以做 conn = current_connection() 或类似的事情作为它的第一步,然后在其余的方法中使用它。
    • 虽然我开始使用上面的示例,但结果仍在缓存中。
    • @Graham Dumpleton 你会碰巧有一些工作的例子吗?也许在你的博客上?
    • 虽然我还不确定.. 看起来我可能已经通过切换到 _mysql 解决了这个问题.. 在我的旧脚本中我有 import _mysql 而不是 import MySQLdb .. 我正在测试它......到目前为止没有缓存工作......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-05
    • 2014-03-10
    • 2012-05-31
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    • 2018-01-18
    相关资源
    最近更新 更多