TypeError: 'int' object is not iterable while trying to decode base62

533 Views Asked by At

I'm trying to write a decode base62 function, but python gives me the error:

TypeError: 'int' object is not iterable

This code works out perfectly outside of flask. but it doesn't work in flask.

The code is below : EDITED:

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

This code works perfectly fine outside of flask, but gives me an error when I call it from my Flask App.

1

There are 1 best solutions below

3
Vlad Lyga On

Try to enforce converting to string, see if it enables you to run without errors, and then check your decoded output - I think at some point you have a string representing a number which is being converted internally by python, and that's where the error comes from:

def base62_decode(s):
    tnum = 0
    for char in str(s):
        tnum = tnum * BASE_LEN + BASE_DICT[char]
    return tnum

Note that this code assumes python 2; python 3 behaves differently when iterating over a string.