@app.route('/restruct', methods=['POST']) def restruct(): dch = request.form['dch'] dch_folder = "restr" + dch count = 1 while os.path.exists(os.path.join('D:\cj', dch_folder)): dch_folder = "restr" + dch + "_" + str(count) count += 1 os.makedirs(os.path.join('D:\cj', dch_folder, 'photos')) os.makedirs(os.path.join('D:\cj', dch_folder, 'kmls')) os.makedirs(os.path.join('D:\cj', dch_folder, 'project')) photos_folder = os.path.join('D:\cj', dch_folder, 'photos') kmls_folder = os.path.join('D:\cj', dch_folder, 'kmls') project_folder = os.path.join('D:\cj', dch_folder, 'project') for file in request.files.getlist('files'): filename = file.filename file.save(os.path.join(photos_folder, filename)) dhs = request.form.getlist('dh') for dh in dhs: src_path = os.path.join(r'D:/911kml/', dh + '.xlsx.kml') dst_path = os.path.join(r'D:/cj', dch_folder, 'kmls/', dh + '.xlsx.kml') shutil.copy(src_path, dst_path) subprocess.Popen(["python", "restruct.py", dch, photos_folder, project_folder, kmls_folder])使用python3.6版本的websocket,在flask框架中将这段代码运行中的输出信息,实时发送给前端,给出前端访问地址
时间: 2023-06-24 18:08:55 浏览: 81
Fingerprint_WBF_USB_DCH_ELAN_Z_V3.5.12201.11001_24387.exe
可以使用 Flask-SocketIO 扩展来实现 WebSocket 实时发送输出信息给前端。
首先,需要在服务器上安装 Flask-SocketIO 扩展:
```
pip install flask-socketio
```
然后,在 Flask 应用程序中导入并初始化 SocketIO:
```python
from flask import Flask, render_template
from flask_socketio import SocketIO
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
```
接下来,在你的视图函数中,需要将输出信息发送给所有连接的 WebSocket 客户端:
```python
import subprocess
@socketio.on('connect')
def test_connect():
print('Client connected')
@app.route('/restruct', methods=['POST'])
def restruct():
# ...
process = subprocess.Popen(["python", "restruct.py", dch, photos_folder, project_folder, kmls_folder], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
print(output.strip())
socketio.emit('output', output.strip())
return render_template('index.html')
```
然后,在前端 HTML 文件中,需要引入 SocketIO JavaScript 库,并连接到服务器:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebSocket Output</title>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="//cdn.socket.io/socket.io-1.2.0.js"></script>
</head>
<body>
<script type="text/javascript" charset="utf-8">
var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on('connect', function() {
console.log('Connected to server');
});
socket.on('output', function(data) {
console.log(data);
});
</script>
</body>
</html>
```
最后,启动 Flask 应用程序并访问前端页面,就可以实现 WebSocket 实时发送输出信息给前端了。需要注意的是,可能需要根据你的服务器环境和项目结构进行适当的修改。
阅读全文