首页 > 解决方案 > 如何修复大写的 Salesforce 18 位 ID

问题描述

如果以全大写格式返回 Salesforce 18 位 ID(例如,由第三方程序),这会使 Salesforce 无法读取 18 位 ID。如何使用 python 来修复这个全大写的 ID?

标签: pythonpython-3.xsalesforce

解决方案


这篇文章是对 Salesforce Stack Exchange 上问题“将大写的 18 位 ID 转换为有效 ID”的重构。此处发布的解决方案将 Adrian Larson 的解决方案转换为将大写 ID 从 APEX 修复为 Python 3。

转换为 Python 3 的 APEX 解决方案:

def getBitPatterns(c):
    CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ012345'
    index = CHARS.find(c)
    result = []
    for bitNumber in range(0,5):
        result.append((index & (1 << bitNumber)) != 0)
    return result

def repairCasing(x18DigitId):
    if len(x18DigitId) < 18:
        return 'Error'
    toUpper = []
    toUpper.append(getBitPatterns(x18DigitId[15:16]))
    toUpper.append(getBitPatterns(x18DigitId[16:17]))
    toUpper.append(getBitPatterns(x18DigitId[17:18]))
    toUpper = [item for sublist in toUpper for item in sublist]

    output = ''.join([x18DigitId[x].upper() if toUpper[x] else x18DigitId[x].lower() for x in range(0,15)]) + x18DigitId[15:].upper()

    return output

例子:

repairCasing('003i000001IIGW7AAH')

出去:

'003i000001IIGw7AAH'

笔记:

对于学习者来说,

toUpper = [item for sublist in toUpper for item in sublist]

是一种将数组中的数组展平为单个数组的列表理解方法(感谢 Alex Martinelli 在How to make a flat list out of list of lists?),相当于:

for sublist in toUpper:
    for item in sublist:
        newList.append(item)
toUpper = newList

相似地:

output = ''.join([x18DigitId[x].upper() if toUpper[x] else x18DigitId[x].lower() for x in range(0,15)]) + x18DigitId[15:].upper()

is the list-comprehension equivalent of:

     output = ''

     for i in range(0,15):
         c = x18DigitId[i:i+1]
         if toUpper[i]:
             output += c.upper()
         else:
             output += c.lower()

     output += x18DigitId[15:18].upper()

推荐阅读