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

如何在Flask中展示字典键为按钮并获取用户输入(Spotify场景)

解决Flask中Spotify播放列表按钮交互的问题

嘿,我来帮你搞定这个需求!核心就是用Flask的Jinja2模板引擎渲染播放列表,再通过表单或AJAX把选中的播放列表ID传回后端脚本。下面分步骤给你详细说明:

1. 后端:传递播放列表数据到模板

首先,确保你的Flask路由已经获取到包含name和id字段的Spotify播放列表,再把这个列表传给渲染的模板。示例代码如下:

from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

# 替换成你实际获取Spotify播放列表的逻辑
def get_spotify_playlists():
    return [
        {"name": "我的每日推荐", "id": "123abc"},
        {"name": "跑步专属歌单", "id": "456def"},
        {"name": "怀旧金曲合集", "id": "789ghi"}
    ]

@app.route('/')
def index():
    playlists = get_spotify_playlists()
    # 把播放列表数据传入模板
    return render_template('playlists.html', playlists=playlists)

2. 前端模板:渲染可点击的播放列表按钮

创建templates/playlists.html模板,用Jinja2的for循环遍历播放列表,把每个列表做成可交互按钮。这里提供两种常用实现方式:

方式一:同步表单提交(简单直接)

每个播放列表对应独立表单,点击按钮时提交表单,把ID传到后端:

<!DOCTYPE html>
<html>
<head>
    <title>我的Spotify播放列表</title>
</head>
<body>
    <h1>选择你的播放列表</h1>
    {% for playlist in playlists %}
        <form action="/select-playlist" method="POST" style="display: inline-block; margin: 5px;">
            <input type="hidden" name="playlist_id" value="{{ playlist.id }}">
            <button type="submit">{{ playlist.name }}</button>
        </form>
    {% endfor %}
</body>
</html>

方式二:AJAX异步请求(无刷新体验)

如果想要页面不刷新就能传ID,用JavaScript的Fetch API实现:

<!DOCTYPE html>
<html>
<head>
    <title>我的Spotify播放列表</title>
</head>
<body>
    <h1>选择你的播放列表</h1>
    {% for playlist in playlists %}
        <button onclick="selectPlaylist('{{ playlist.id }}')" style="margin: 5px;">{{ playlist.name }}</button>
    {% endfor %}

    <script>
        function selectPlaylist(playlistId) {
            fetch('/select-playlist', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ playlist_id: playlistId }),
            })
            .then(response => response.json())
            .then(data => {
                console.log('成功提交播放列表ID:', data);
                // 可添加成功提示等后续逻辑
            })
            .catch(error => {
                console.error('提交出错:', error);
            });
        }
    </script>
</body>
</html>

3. 后端:接收并处理播放列表ID

添加一个路由接收前端传来的ID,进行后续业务处理:

@app.route('/select-playlist', methods=['POST'])
def select_playlist():
    # 表单提交用request.form获取ID
    # playlist_id = request.form.get('playlist_id')
    
    # AJAX JSON提交用request.get_json()获取ID
    data = request.get_json()
    playlist_id = data.get('playlist_id')

    if playlist_id:
        # 这里写拿到ID后的逻辑,比如获取该播放列表的歌曲信息
        print(f"用户选择的播放列表ID: {playlist_id}")
        # AJAX方式需要返回JSON响应
        return jsonify({"status": "success", "playlist_id": playlist_id})
    else:
        return jsonify({"status": "error", "message": "未获取到播放列表ID"}), 400

这样就能实现你想要的效果:用户看到所有播放列表名称的按钮,点击后对应ID会传回Flask脚本,你就可以用这个ID做后续操作啦!

内容的提问来源于stack exchange,提问作者Mr. Dulla

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:09:53