处理 Llong BLOBS 并生成随机图像

问题描述

使用 Python 制作摄影网站。我构建了以下函数来从 MysqL 中的图像表生成随机图像。这是函数 似乎我的图像在从数据库返回后被处理为字符串,我不知道为什么。有人介意帮助我吗?我正在使用 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