使用Flask实现XML文件上传处理及Python代码生成问题咨询
Flask XML上传保存问题修复方案
你代码中存在以下核心问题导致XML文件无法正常保存:
- 缺失依赖导入:使用了
xmltodict但代码开头没有导入该库 - 文件获取逻辑错误:前端上传的文件应该通过
request.files获取,你直接用request.get_data()把二进制内容传给xmltodict.parse得到的是字典对象,没有save()方法,无法调用保存接口 - 未配置上传目录:
app.config['upload']没有提前定义,也没有预先创建upload、tmp两个工作目录,写入路径不存在 - 路由重复冲突:两个视图函数都绑定了
/submit/路径,后定义的convert会覆盖之前的POST上传路由,上传请求根本进不到处理逻辑 - 路径操作不规范:滥用
os.chdir修改工作目录容易出现相对路径混乱,用反斜杠\拼接路径仅适配Windows,跨平台运行会报错 - 逻辑断层:你上传的是XML文件,但convert逻辑里只遍历后缀为.py的文件,完全不会处理上传的XML,也没法生成后续代码
修复步骤
- 先安装缺失依赖:
pip install flask xmltodict - 修正后的完整代码:
from flask import Flask, request, render_template import xmltodict from main import run import os app = Flask(__name__, template_folder='templates') # 提前配置路径并自动创建工作目录 BASE_DIR = os.path.abspath(os.path.dirname(__file__)) UPLOAD_FOLDER = os.path.join(BASE_DIR, 'upload') TMP_FOLDER = os.path.join(BASE_DIR, 'tmp') os.makedirs(UPLOAD_FOLDER, exist_ok=True) os.makedirs(TMP_FOLDER, exist_ok=True) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config['TMP_FOLDER'] = TMP_FOLDER @app.route('/') def home(): return render_template('home.html') # 拆分上传和转换路由避免冲突 @app.route('/upload/', methods=['POST']) def upload(): if request.method == 'POST': # 从表单文件域获取上传的XML,此处file对应前端表单input的name属性 if 'file' not in request.files: return "未检测到上传文件", 400 uploaded_file = request.files['file'] if uploaded_file.filename == '': return "未选择文件", 400 if uploaded_file and uploaded_file.filename.endswith('.xml'): save_path = os.path.join(app.config['UPLOAD_FOLDER'], uploaded_file.filename) uploaded_file.save(save_path) return "Successfully uploaded" return "上传失败", 400 @app.route('/convert/') def convert(): upload_path = app.config['UPLOAD_FOLDER'] # 遍历XML文件生成代码 for file_name in os.listdir(upload_path): if file_name.endswith(".xml"): file_path = os.path.join(upload_path, file_name) # 调用自定义run逻辑生成Python代码到tmp目录 run(file_path, app.config['TMP_FOLDER'], 'python') return "Code generated" @app.route('/view/') def view_python_script(): tmp_path = app.config['TMP_FOLDER'] content = "" for file_name in os.listdir(tmp_path): if file_name.endswith(".py"): file_path = os.path.join(tmp_path, file_name) with open(file_path, "r", encoding='utf-8') as f: content = content + f.read().replace('\n','<br>') return render_template('upload.html', details=content) if __name__ == "__main__": app.run(port=3000, debug=True)
额外注意事项
前端上传文件的表单必须添加enctype="multipart/form-data"属性,否则request.files无法正常获取上传文件。
内容的提问来源于stack exchange,提问作者Nishani Kasineshan
相关产品推荐
相关产品推荐

