TypeError: 'int'对象不可迭代,解码base62时出错
我正在尝试写一个 解码 base62
的函数,但在 Python 中出现了错误:
TypeError: 'int' object is not iterable
这段代码在 Flask 之外运行得很好,但在 Flask 中却不行。
下面是代码:已编辑:
BASE_ALPH = tuple("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
BASE_DICT = dict((c, v) for v, c in enumerate(BASE_ALPH))
BASE_LEN = len(BASE_ALPH)
def base62_decode(string):
tnum = 0
for char in str(string):
tnum = tnum * BASE_LEN + BASE_DICT[char]
return tnum
def base62_encode(num):
if not num:
return BASE_ALPH[0]
if num<0:
return False
num = int(num)
encoding = ""
while num:
num, rem = divmod(num, BASE_LEN)
encoding = BASE_ALPH[rem] + encoding
return encoding
这段代码在 Flask 之外完全没问题,但当我在 Flask 应用中调用它时却出现了错误。
1 个回答
0
试着强制把内容转换成字符串,看看这样能否顺利运行而不出错,然后检查一下你解码后的输出。我觉得在某个环节,你有一个表示数字的字符串,Python 在内部把它转换了,这就是出错的地方:
def base62_decode(s):
tnum = 0
for char in str(s):
tnum = tnum * BASE_LEN + BASE_DICT[char]
return tnum
注意,这段代码是基于 Python 2 的;在 Python 3 中,遍历字符串的方式是不同的。