You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从MySQL数据库检索上传图片失败:Django环境下技术求助

问题:从MySQL数据库检索图片传入主色调提取程序失败

我正在开发一个网站,用户上传图片后网站会返回图片中的10种主要颜色。目前已成功将图片上传至MySQL数据库,但在从数据库检索图片并传入主色调提取程序时遇到问题。我使用Django实现了MySQL、Python与HTML的连接,相关代码如下:

import base64
import io
from PIL import Image
up_im=""
cap=""
# Create your views here.
def starttest(request):
    if request.method=="POST":
        global up_im,cap
        con=sql.connect(host="localhost", user="root", passwd="****", database='test_pro',auth_plugin='mysql_native_password',buffered=True)
        cursor=con.cursor()
        pos=request.POST
        for key,value in pos.items():
            if key=='IMAGE':
                up_im=value
            if key=="caption":
                cap=value
        c="insert into userdata values('{}','{}')".format(up_im,cap)
        cursor.execute(c)
        retr="select IMAGE from userdata where caption= '{}'".format(cap)
        cursor.execute(retr)
        data=cursor.fetchone()
        uploaded_image=data[0][0]
        binary_data=base64.b64decode(uploaded_image)
        show_image=Image.open(io.BytesIO(binary_data))
        show_image.show()
        con.commit()

错误情况

执行代码时触发tuple index out of range错误,错误指向uploaded_image=data[0][0]这一行。

参考教程内容(翻译)

参考教程介绍了如何使用Python从MySQL表中检索以Blob格式存储的图片和文件,核心流程为读取Blob字段数据后,将其转换为二进制流,再通过PIL库打开图片。

解决步骤

  • 修正索引错误:fetchone()返回的是单条记录的元组,比如查询IMAGE字段后,data格式为(二进制数据,),因此直接取data[0]即可,删除多余的[0],代码改为:
    uploaded_image = data[0]
    
  • 修复SQL注入风险:不要用字符串格式化拼接SQL语句,改用参数化查询:
    插入语句修改为:
    c = "insert into userdata (IMAGE, caption) values (%s, %s)"
    cursor.execute(c, (up_im, cap))
    
    查询语句修改为:
    retr = "select IMAGE from userdata where caption = %s"
    cursor.execute(retr, (cap,))
    
  • 移除不必要的全局变量:up_im和cap直接在函数内部定义使用即可,避免多请求之间的变量污染。
  • 优化数据库连接管理:使用with语句自动管理连接和游标,确保资源正确释放:
    def starttest(request):
        if request.method=="POST":
            with sql.connect(host="localhost", user="root", passwd="****", database='test_pro',auth_plugin='mysql_native_password',buffered=True) as con:
                with con.cursor() as cursor:
                    pos = request.POST
                    up_im = pos.get('IMAGE', '')
                    cap = pos.get('caption', '')
                    # 插入操作
                    c = "insert into userdata (IMAGE, caption) values (%s, %s)"
                    cursor.execute(c, (up_im, cap))
                    # 查询操作
                    retr = "select IMAGE from userdata where caption = %s"
                    cursor.execute(retr, (cap,))
                    data = cursor.fetchone()
                    if data:
                        uploaded_image = data[0]
                        binary_data = base64.b64decode(uploaded_image)
                        show_image = Image.open(io.BytesIO(binary_data))
                        show_image.show()
                    con.commit()
    

内容的提问来源于stack exchange,提问作者Tharun nivek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 01:05:34