【问题标题】:CherryPy and MySQL can't connect to the databaseCherryPy 和 MySQL 无法连接数据库
【发布时间】:2013-01-23 23:07:48
【问题描述】:

我在 Apache 下使用 modwsgi 建立了一个 CherryPy“站点”。它工作正常,我可以毫无问题地返回 hello world 消息。问题是当我尝试连接到我的 MySQL 数据库时。这是我正在使用的代码。

import sys
sys.stdout = sys.stderr

import atexit
import threading
import cherrypy

import MySQLdb

cherrypy.config.update({'environment': 'embedded'})

if cherrypy.__version__.startswith('3.0') and cherrypy.engine.state == 0:
    cherrypy.engine.start(blocking=False)
    atexit.register(cherrypy.engine.stop)

def initServer():
    global db
    db=MySQLdb.connect(host="localhost", user="root",passwd="pass",db="Penguin")

class Login(object):
    def index(self):
        return 'Login Page'
    index.exposed = True

class Root(object):
    login = Login();

    def index(self):
        # Sample page that displays the number of records in "table" 
        # Open a cursor, using the DB connection for the current thread 
        c=db.cursor()
        c.execute('SELECT count(*) FROM Users')
        result=cursor.fetchall()
        cursor.close()

        return 'Help' + result

    index.exposed = True


application = cherrypy.Application(Root(), script_name=None, config=None)

大部分内容是在设置 modwsgi 时从 CherryPy 网站复制的,我只是添加了从各种互联网资源拼凑而成的数据库内容。

当我尝试查看根页面时,我收到 500 内部服务器错误。我仍然可以正常进入登录页面,但我很确定我以某种方式搞乱了数据库连接。

【问题讨论】:

  • 有些东西必须调用 initServer。你在哪里做的?

标签: python mysql cherrypy


【解决方案1】:

你有一堆错误,实际上与 CherryPy 无关。

def initServer():
    global db

db 未在全局范围内定义。试试:

db = None
def initServer():
    global db

此外,永远不会调用initServer() 来创建数据库连接。

另一个:

c = db.cursor()
c.execute('SELECT count(*) FROM Users')
result = cursor.fetchall()
cursor.close()

cursor 未定义。我想你的意思是c

c = db.cursor()
c.execute('SELECT count(*) FROM Users')
result = c.fetchall()
c.close()

【讨论】:

  • 是的,我最大的错误是我在 fetchAll 上使用 cursor 而不是 c 并关闭。错别字,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-01
  • 2016-12-03
  • 2014-01-25
  • 1970-01-01
  • 1970-01-01
  • 2020-07-21
相关资源
最近更新 更多