处理 Llong BLOBS 并生成随机图像

Handling Llong BLOBS and generating a random image

用Python做一个摄影网站。我构建了以下函数来从 mYSQL 中的 Table 个图像中生成随机图像。这是函数从数据库返回后,我的图像似乎被处理为字符串,我不明白为什么。有人介意帮助我吗?我正在使用 Python Flask 库,并且 SQL 炼金术作为 ORM

def generateRandomPhotoObject():

    # Query photo table for all entries
    obj = Photo.query.all()
    if len(obj) == 0:
        return
    # Choose a random entry from the table
    randomNumber = random.randint(0, len(obj) - 1)
    randomPhotoObject = obj[randomNumber]
    tempImage = randomPhotoObject.image
    tempImage = b64encode(tempImage).decode("utf-8")
    randomPhotoObject.image = tempImage
    return randomPhotoObject

此函数运行并出现以下错误:

TypeError: a bytes-like object is required, not 'str'

我相信我找到了解决方案。我只是检查了类型是否为字符串,然后对其进行了相应的编码。

def generateRandomPhotoObject():

    # Query photo table for all entries
    obj = Photo.query.all()
    if len(obj) == 0:
        return
    # Choose a random entry from the table
    randomNumber = random.randint(0, len(obj) - 1)
    randomPhotoObject = obj[randomNumber]
    if type(randomPhotoObject.image) == str:
        tempImage = bytes(randomPhotoObject.image, encoding='utf-8')
    else:
        tempImage = b64encode(randomPhotoObject.image)
    tempImage = tempImage.decode("utf-8")
    randomPhotoObject.image = tempImage
    return randomPhotoObject