如何在Django中运行外部Python脚本并在前端以表格展示JSON数据
在Django中运行外部Python脚本并展示JSON测试数据为表格
1. 后端实现:运行外部脚本并处理JSON数据
在Django的app中编写视图函数,负责调用外部Python脚本、解析输出的JSON数据。使用subprocess模块执行脚本时,必须用绝对路径指定脚本位置,避免安全风险。
示例视图代码:
# your_app/views.py import subprocess import json from django.shortcuts import render from django.http import JsonResponse def regression_test_results(request): # 外部脚本的绝对路径 script_path = "/absolute/path/to/your/test_script.py" try: # 运行脚本并捕获输出 result = subprocess.run( ["python", script_path], capture_output=True, text=True, check=True # 脚本执行失败时抛出异常 ) # 解析JSON输出 test_data = json.loads(result.stdout) # 区分AJAX请求和普通请求,分别返回JSON或渲染模板 if request.headers.get('X-Requested-With') == 'XMLHttpRequest': return JsonResponse(test_data, safe=False) return render(request, 'test_results.html', {'test_data': test_data}) except subprocess.CalledProcessError as e: error_msg = f"脚本执行失败: {e.stderr}" return render(request, 'test_results.html', {'error': error_msg}) except json.JSONDecodeError: return render(request, 'test_results.html', {'error': "脚本输出不是合法的JSON格式"})
2. 配置路由
在app的urls.py中添加对应路由:
# your_app/urls.py from django.urls import path from . import views urlpatterns = [ path('test-results/', views.regression_test_results, name='test_results'), ]
3. 前端模板渲染表格
创建模板文件templates/test_results.html,遍历JSON数据生成HTML表格。假设脚本输出为字典列表(每个字典对应一行测试数据):
<!DOCTYPE html> <html> <head> <title>回归测试结果</title> <style> table {border-collapse: collapse; width: 80%; margin: 20px auto;} th, td {border: 1px solid #ddd; padding: 8px; text-align: left;} th {background-color: #f2f2f2;} </style> </head> <body> <h1 style="text-align: center;">回归测试结果</h1> {% if error %} <p style="color: red; text-align: center;">{{ error }}</p> {% else %} <table> <thead> <tr> <!-- 动态生成表头 --> {% if test_data %} {% for key in test_data.0.keys %} <th>{{ key }}</th> {% endfor %} {% endif %} </tr> </thead> <tbody> {% for row in test_data %} <tr> {% for value in row.values %} <td>{{ value }}</td> {% endfor %} </tr> {% endfor %} </tbody> </table> {% endif %} <!-- 可选:添加动态刷新按钮 --> <button id="refresh-btn" style="display: block; margin: 0 auto;">重新运行测试</button> <script> document.getElementById('refresh-btn').addEventListener('click', function() { fetch('{% url "test_results" %}', { headers: {'X-Requested-With': 'XMLHttpRequest'} }) .then(response => response.json()) .then(data => { const tableBody = document.querySelector('tbody'); const tableHead = document.querySelector('thead tr'); tableHead.innerHTML = ''; tableBody.innerHTML = ''; // 重新生成表头 Object.keys(data[0]).forEach(key => { const th = document.createElement('th'); th.textContent = key; tableHead.appendChild(th); }); // 重新生成表格行 data.forEach(row => { const tr = document.createElement('tr'); Object.values(row).forEach(value => { const td = document.createElement('td'); td.textContent = value; tr.appendChild(td); }); tableBody.appendChild(tr); }); }) .catch(error => alert('刷新失败: ' + error)); }); </script> </body> </html>
关键安全注意事项
- 脚本路径必须用绝对路径,禁止使用用户输入的路径,防止命令注入;
- 限制
subprocess.run的参数,避免传递不可信内容; - 给视图添加权限控制(比如
@login_required装饰器),仅允许授权用户执行脚本; - 捕获所有异常,避免暴露服务器内部信息。
内容的提问来源于stack exchange,提问作者AISHWARYA GUPTA
相关产品推荐
相关产品推荐

