CherryPy与MySQL无法连接数据库

0 投票
1 回答
1694 浏览
提问于 2025-04-17 13:28

我在Apache服务器上用mod_wsgi设置了一个CherryPy网站,一切运行得很好,能顺利返回“你好,世界”的信息。问题出现在我尝试连接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)

大部分代码都是从CherryPy网站上关于设置mod_wsgi的部分复制过来的,我只是加了一些数据库的内容,这些内容是我从各种网络资源拼凑而来的。

当我尝试查看主页时,出现了500内部服务器错误。不过我可以正常访问登录页面,所以我觉得我在数据库连接上搞错了什么。

1 个回答

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()

撰写回答