在Python中处理从SOQL提取的Unicode字符串

在Python中处理从SOQL提取的Unicode字符串,python,unicode,ascii,soql,Python,Unicode,Ascii,Soql,代码的目的是使用SOQL查询SalesForce API,然后格式化数据并在将其放入oracle数据库之前执行一些操作。我的代码成功地处理了第一部分和第三部分,但第二部分不断中断 该代码在Windows7上使用Python2.7和标准的C Python编译器 SOQL是 SELECT ID, Name, Type, Description, StartDate, EndDate, Status FROM CAMPAIGN ORDER BY ID 这个查询在JSON Dic

代码的目的是使用SOQL查询SalesForce API,然后格式化数据并在将其放入oracle数据库之前执行一些操作。我的代码成功地处理了第一部分和第三部分,但第二部分不断中断

该代码在Windows7上使用Python2.7和标准的C Python编译器

SOQL是

SELECT  ID, Name, Type, Description, StartDate, EndDate, Status
FROM        CAMPAIGN
ORDER BY    ID
这个查询在JSON Dict中返回几百个结果。 我必须一次提取一条记录(记录包含ID、名称、类型、描述、开始日期、结束日期和状态),并将它们传递给生成适当SQL的函数,以便将数据放入适当的Oracle数据库中。查询的所有结果都以Unicode字符串的形式返回

在查询数据并尝试将其传递给函数以生成SQL并将其插入Oracle数据库之后,问题就出现了

下面是发生错误的代码部分

keys = ['attributes', 'Id', 'Name', 'Type', 'Description', 'StartDate', 'EndDate', 'Status']
for record in SrcData['records']:  #Data cleaning in this loop. 
    processedRecs = []
    if record['Description'] is not None:                
        record['Description'] = encodeStr(record['Description'])
        record['Description'] = record['Description'][0:253]

    for key in keys:
        if key == 'attributes':
            continue
        elif key == 'StartDate' and record[key] is not None:
            record[key] = datetime.datetime.strptime(record[key], "%Y-%m-%d")
        elif key == 'EndDate' and record[key] is not None:
            record[key] = datetime.datetime.strptime(record[key], "%Y-%m-%d")
        else:
            pass

        processedRecs.append(record[key])

    sqlFile.seek(0)
    Query = RetrieveSQL(sqlFile, processedRecs)
密钥列表是因为SrcData.keys()上的循环出现问题。 encodeStr功能是:

def encodeStr(strToEncode):
    if strToEncode == None:
        return ""
    else:
        try:
            tmpstr = strToEncode.encode('ascii', 'ignore')
            tmpstr = ' '.join(tmpstr.split())
            return tmpstr 
        except:
            return str(strToEncode)
我收到的错误消息是:

Traceback (most recent call last): File "XXX", line 106, in Query = ASPythonLib.RetrieveSQL(sqlFile, processedRecs), UnicodeEncodeError: ascii codec cant encode character u\u2026 in position 31: ordinal not in range(128)
XXXX只是一个文件路径,它指向代码在我们的文件系统中的位置。老板说我必须把这条路移走

我还尝试了以下多种变体:

record['Description'] = record['Description'].encode('ascii', 'ignore').decode(encoding='ascii',errors='strict')
我尝试过交换编码和解码函数的顺序。我尝试了不同的编解码器和不同的错误处理方案

****编辑****此代码与其他20个周期一样正常工作,因此可以安全地假设错误不在RetrieveSQL()中。 以下是RetrieveSQL的代码:

def RetrieveSQL(SQLFile, VarList, Log = None):
    SQLQuery = SQLFile.readline()

    FileArgs = [""]

    NumArgValues = len(VarList)

    if( "{}" in SQLQuery ):
        # NumFileArgs == 0
        if (NumArgValues != 0):
            print "Number of File Arguments is zero for File " + str(SQLFile) + " is NOT equal to the number of values provided per argument (" + str(NumArgValues) + ")."
        return SQLFile.read()
    elif( SQLQuery[0] != "{" ):
        print "File " + str(SQLFile) + " is not an SQL source file."
        return -1

    elif( SQLQuery.startswith("{") ):
        FileArgs = SQLQuery.replace("{", "").replace("}", "").split(", ")
        for Arg in xrange(0, len(FileArgs)):
            FileArgs[Arg] = "&" + FileArgs[Arg].replace("\n", "").replace("\t", "") + "&" # Add &'s for replacing

    NumFileArgs  = len(FileArgs)

    if (NumFileArgs != NumArgValues):
        if (NumArgValues == 0):
            print "No values were supplied to RetrieveSQL() for File " + str(SQLFile) + " when there were supposed to be " + str(NumFileArgs) + " values."
            return -1
        elif (NumArgValues > 0):
            "Number of File Arguments (" + str(NumFileArgs) + ") for File " + str(SQLFile) + " is NOT equal to the number of values provided per argument (" + str(NumArgValues) + ")."
            return -1

    SQLQuery = SQLFile.read()
    VarList = list(VarList)
    for Arg in xrange(0, len(FileArgs)):
            if (VarList[Arg] == None):
                SQLQuery = SQLQuery.replace(FileArgs[Arg], "NULL")
            elif ("'" in str(VarList[Arg])):
                SQLQuery = SQLQuery.replace(FileArgs[Arg], "'" + VarList[Arg].replace("'", "''") + "'")
            elif ("&" in str(VarList[Arg])):
                SQLQuery = SQLQuery.replace(FileArgs[Arg], "'" + VarList[Arg].replace("&", "&'||'") + "'")
            elif (isinstance(VarList[Arg], basestring) == True):
                VarList[Arg] = VarList[Arg].replace("'", "''")
                SQLQuery = SQLQuery.replace(FileArgs[Arg], "'" + VarList[Arg] + "'")
            else:
                SQLQuery = SQLQuery.replace(FileArgs[Arg], str(VarList[Arg]))
    SQLFile.seek(0)

    return SQLQuery
****编辑#2****
尝试在日志文件中查找完整的回溯,但此脚本的日志系统非常糟糕,记录的日志不会超过“循环成功”或“循环失败”。啊,重写由不懂编码的人编写的代码的乐趣

这是一个完整的回溯吗?什么是
RetrieveSQL
?是的,这是一个完整的回溯。RetrieveSQL是一个使用模板SQL文件生成SQL查询的函数?然后你的追踪会更进一步。格式不完整,没有命名的模块或函数,没有前面的行等,不应使用模板将数据插入SQL查询;您希望使用SQL参数并将插值留给数据库驱动程序。请确实显示实际的回溯;当前信息不足以诊断问题。