4
def websvc(currency):
    db = MySQLdb.connect("localhost", "root", "aqw", "PFE_Project")
    cursor = db.cursor()
    sql = "SELECT * FROM myform_composantsserveur"
        
    try:
        cursor.execute(sql)
        results = cursor.fetchall()
        currency_in = currency
        req = urllib2.urlopen('http://rate-exchange.appspot.com/currency?from=USD&to=%s') % (currency_in) 
        req1 = req.read()
        rate = int(req1['rate'])
        # rate = 0.77112893299999996
        
        servers = []
        for row in results:
            result = {} 
            result['1'] = row[1]
            result['3'] = int(row[2])
            result['4'] = int(row[3])
            result['5'] = int(row[4])
            result['6'] = row[5]
            result['7'] = int(row[6])
            result['8'] = row[7]
            result['9'] = row[8]
            p = rate * calculations_metric (int(row[2]), int(row[3]), int(row[4]), int(row[6]), row[7])
            result['2'] = p
            keys = result.keys()
            keys.sort()
            servers.append(result)
             
    except:
        print "Error: unable to fetch data"
    db.close()
    return servers

但是我在编译代码时遇到了这个错误:

异常类型:UnboundLocalError

异常值:分配前引用的局部变量“服务器”

异常位置:/home/amine/PFE Directory/mysite1/myform/Webservice.py in websvc,第 43 行 Python 可执行文件:/usr/bin/python2.7

在我在此函数中添加参数之前,此代码正常工作

4

2 回答 2

5

您的代码无法访问服务器初始化,这就是您收到错误的原因。只需在 try..except 之前移动初始化。改变这种方式:

def websvc(currency):
    db = MySQLdb.connect("localhost", "root", "aqw", "PFE_Project")
    cursor = db.cursor()
    sql = "SELECT * FROM myform_composantsserveur"
    servers = []

    try:
        cursor.execute(sql)
        results = cursor.fetchall()
        currency_in = currency
        req = urllib2.urlopen('http://rate-exchange.appspot.com/currency?from=USD&to=%s') % (currency_in) 
        req1 = req.read()
        rate = int(req1['rate'])
        # rate = 0.77112893299999996

        for row in results:
            result = {} 
            result['1'] = row[1]
            result['3'] = int(row[2])
            result['4'] = int(row[3])
            result['5'] = int(row[4])
            result['6'] = row[5]
            result['7'] = int(row[6])
            result['8'] = row[7]
            result['9'] = row[8]
            p = rate * calculations_metric (int(row[2]), int(row[3]), int(row[4]), int(row[6]), row[7])
            result['2'] = p
            keys = result.keys()
            keys.sort()
            servers.append(result)

    except:
        print "Error: unable to fetch data"
    db.close()
    return servers
于 2013-03-14T10:11:09.613 回答
0

我现在看到了问题,您已经对其进行了编辑以添加缺失的部分。它是异常处理程序。

try如果你之前和之后有错误servers=[]会跳转到except子句,那么看看就return servers失败了。

您可能想使用 a list(),而不是使用 adict()来模拟列表...

于 2013-03-14T10:12:09.363 回答