Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python CherryPy和MySQL可以';无法连接到数据库_Python_Mysql_Cherrypy - Fatal编程技术网

Python CherryPy和MySQL可以';无法连接到数据库

Python CherryPy和MySQL可以';无法连接到数据库,python,mysql,cherrypy,Python,Mysql,Cherrypy,我在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

我在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)
大部分内容都是从CherryPy网站上复制的,我只是添加了数据库的内容,这些内容是我从各种互联网来源拼凑而成的


当我试图查看根页面时,我得到一个500内部服务器错误。我仍然可以很好地进入登录页面,但我很确定我不知怎么搞砸了数据库连接。

你有一大堆错误,与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()
未定义光标。我想你的意思是
c

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

必须调用initServer。你在哪里这么做?我最大的错误是,我在fetchAll和close上使用了cursor而不是c。愚蠢的打字错误,谢谢