Python Flask如何从下拉列表获取选中音乐文件名实现播放
代码修改说明
你需要修改两处核心代码,即可实现选中曲目触发播放的逻辑,原有style.css无需调整:
1. 修改后的app.py
from flask import Flask, render_template, request, redirect, url_for import os import subprocess app = Flask(__name__) # 统一配置音乐目录,方便后续修改 MUSIC_DIR = '/var/lib/mpd/music/' @app.route('/') def index(): # 过滤只保留音乐文件,排除子目录 files = [f for f in os.listdir(MUSIC_DIR) if os.path.isfile(os.path.join(MUSIC_DIR, f))] return render_template('index.html', files=files) @app.route('/play', methods=['POST']) def play(): selected_track = request.form.get('files') # 安全校验,防止恶意路径遍历攻击 if selected_track and os.path.exists(os.path.join(MUSIC_DIR, selected_track)): # 调用mpc命令播放,这里用subprocess比os.system更安全,避免命令注入风险 subprocess.run(['mpc', 'clear'], check=True) subprocess.run(['mpc', 'add', selected_track], check=True) subprocess.run(['mpc', 'play'], check=True) # 操作完成后返回首页 return redirect(url_for('index')) if __name__ == '__main__': app.run(debug=False, host='0.0.0.0')
2. 修改后的index.html
原代码把method和action属性错写在了select标签上,这两个属性属于form标签,需要补全表单结构并添加播放按钮:
<html> <head> <link rel="stylesheet" href='/static/style.css' /> </head> <body> <center> <h1>Music Website</h1> <hr> <h2>Select track:</h2> <form method="POST" action="/play"> <select name="files"> <option value="{{files[0]}}" SELECTED>{{files[0]}}</option> {% for fil in files[1:] %} <option value="{{fil}}">{{fil}}</option> {% endfor %} </select> <br><br> <button type="submit" class="button">播放选中曲目</button> </form> <hr> <div class="footer"> <p>Made by Agree Denmark</p> </div> </center> </body> </html>
运行注意事项
- 请确保你的服务器已经正确安装配置了mpd和mpc工具
- 运行Flask服务的用户需要有mpc命令的调用权限,以及
/var/lib/mpd/music/目录的读取权限
内容的提问来源于stack exchange,提问作者AgreeDK
相关产品推荐
相关产品推荐

