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

Flask项目中如何从数据库显示用户头像?

问题分析与修改方案

你的代码存在几个核心问题,导致头像无法显示,以下是针对性的修改步骤:


1. 修正数据库字段名不一致问题

插入账号时使用的字段是picture,但查询时用的是foto,两者必须统一。假设数据库表字段为picture,修改查询语句:

# querys.py 中 get_foto 函数
def get_foto(id):
    cursor = mysql.connection.cursor()
    # 将 SELECT foto 改为 SELECT picture,与插入语句字段统一
    cursor.execute(""" SELECT picture FROM conta WHERE id = %s""", [id])
    result = cursor.fetchone()
    cursor.close()
    # 返回查询到的图片数据,无数据则返回默认头像路径
    return result[0] if result else "static/img/pngwing.com.png"

2. 修复get_foto函数返回值错误

原函数返回的是cursor.execute()的执行行数(整数),而非图片数据,必须改为返回查询结果:

# 修正后的完整get_foto函数
def get_foto(id):
    cursor = mysql.connection.cursor()
    cursor.execute(""" SELECT picture FROM conta WHERE id = %s""", [id])
    result = cursor.fetchone()
    cursor.close()
    return result[0] if result else "static/img/pngwing.com.png"

3. 更换头像存储方式(推荐存文件路径)

用matplotlib.imread()读取的是numpy数组,无法直接在前端显示。推荐直接存储静态文件路径到数据库,更高效且易维护:

# querys.py 中 inserir_conta_jogador 函数
def inserir_conta_jogador(email, password, coach, player):
    cursor = mysql.connection.cursor()
    # 直接存储默认头像的静态文件路径
    default_avatar_path = "static/img/pngwing.com.png"
    inserir_conta_no_banco = cursor.execute(""" INSERT INTO conta (email, password, coach, player, picture) VALUES (%s, %s, %s, %s, %s)""", (email, password, coach, player, default_avatar_path))
    mysql.connection.commit()
    cursor.close()

4. 前端模板正确生成图片URL

Flask中访问静态文件需要用url_for()生成合法路径,修改HTML代码:

{% if user %}
  <h1> ID LOGGED: {{ user }}</h1>
  <!-- 使用url_for生成静态文件的正确URL -->
  <img src="{{ url_for('static', filename=foto) }}" alt="Perfil">
{% else %}
  <h1> NOBODY LOGGED IN </h1>
{% endif %}

可选方案:存储Base64编码(若必须存二进制到数据库)

如果一定要把图片二进制数据存到数据库,需将图片转为Base64编码字符串:

存储时修改:

import base64

def inserir_conta_jogador(email, password, coach, player):
    cursor = mysql.connection.cursor()
    # 读取图片并转为Base64字符串
    with open("website/static/img/pngwing.com.png", "rb") as img_file:
        base64_avatar = base64.b64encode(img_file.read()).decode('utf-8')
    inserir_conta_no_banco = cursor.execute(""" INSERT INTO conta (email, password, coach, player, picture) VALUES (%s, %s, %s, %s, %s)""", (email, password, coach, player, base64_avatar))
    mysql.connection.commit()
    cursor.close()

前端显示修改:

{% if user %}
  <h1> ID LOGGED: {{ user }}</h1>
  <!-- 添加Base64图片前缀 -->
  <img src="data:image/png;base64,{{ foto }}" alt="Perfil">
{% else %}
  <h1> NOBODY LOGGED IN </h1>
{% endif %}

内容的提问来源于stack exchange,提问作者Felipe Wai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 15:12:42