效果圖
先看運行效果圖 OK,下面開始。
安裝環(huán)境
本人使用環(huán)境及版本:
Anaconda:
虛擬環(huán)境:
Python版本:3.8.13
安裝包及版本:
Flask-SocketIO:5.3.4
eventlet:0.33.3
快速開始
后端代碼
創(chuàng)建app.py文件(文件名隨意,不過要與后面的運行腳本中指定的文件保持一致)
import time
from flask import Flask, render_template, jsonify
from flask_socketio import SocketIO
service_state = 0
app = Flask(__name__)
socketio = SocketIO(app, cors_allowed_origins="*")
@app.route("/")
def index():
return render_template("index.html")
@app.route("/start_service")
def start_service():
global service_state
service_state = 0
while service_state == 0:
time_text = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time())))
print(">>>>>>", time_text)
json_data = {"no": 1, "time": time_text, "msg": "......"}
socketio.emit("service_msg", json_data)
socketio.sleep(2)
return jsonify({"start": True})
@app.route("/stop_service")
def stop_service():
global service_state
service_state = 9
return jsonify({"stop": True})
if __name__ == "__main__":
socketio.run(app, host="0.0.0.0", port=5200, debug=True, log_output=True)
前端代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<title>HCI Application</title>
<link rel="apple-touch-icon" sizes="76x76" href="{{url_for('static', filename='img/favicon.ico')}}">
<link rel="icon" type="image/png" href="{{url_for('static', filename='img/favicon.ico')}}">
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0, shrink-to-fit=no' name='viewport'/>
<!-- Font Awesome Icons -->
<link rel="stylesheet" href="{{url_for('static', filename='fontawesome/css/all.css')}}">
<!-- Main CSS -->
<link rel="stylesheet" href="{{url_for('static', filename='css/main.css')}}"/>
<!-- Animation CSS -->
<link rel="stylesheet" href="{{url_for('static', filename='css/vendor/aos.css')}}"/>
</head>
<body>
<!---------- NAVBAR ---------->
<nav class="navbar navbar-expand-lg navbar-dark bg-purple fixed-top">
<div class="container-fluid">
<a class="navbar-brand" href="#"><i class="fas fa-robot mr-2"></i><strong>HCI</strong> Application</a>
<div class="navbar-collapse collapse" id="navbarColor02">
<ul class="navbar-nav ml-auto d-flex align-items-center">
<li class="nav-item">
<input type="hidden" id="running_state" value="0">
<button type="button"
class="btn btn-block btn-primary btn-round mb-1"
id="btn_running_state"
onclick="run_serivce()">
<i class="fas fa-play" id="i_running_state_icon"></i>
<b id="b_running_state_text">啟動服務</b>
</button>
</li>
</ul>
</div>
</div>
</nav>
<!-- End Navbar -->
<main class="container-fluid">
<div class="position-relative">
<div class="container-fluid text-dark mt-5 pt-5">
<!-- table -->
<table class="table table-left table-hover" id="tbl_log">
<thead class="bg-primary text-white">
<tr align="left">
<th scope="col" style="width:120px;">#</th>
<th scope="col" style="width:300px;">Time</th>
<th scope="col">消息內(nèi)容</th>
</tr>
</thead>
<tbody>
<tr align="center" class="text-black">
<th scope="row" colspan="3">等待啟動 ...</th>
</tr>
</tbody>
</table>
</div>
</div>
</main>
<!------------ JAVASCRIPTS ---------------->
<script src="{{url_for('static', filename='js/vendor/jquery.min.js')}}" type="text/javascript"></script>
<script src="{{url_for('static', filename='js/vendor/popper.min.js')}}" type="text/javascript"></script>
<script src="{{url_for('static', filename='js/vendor/bootstrap.min.js')}}" type="text/javascript"></script>
<script src="{{url_for('static', filename='js/vendor/share.js')}}" type="text/javascript"></script>
<script src="{{url_for('static', filename='js/functions.js')}}" type="text/javascript"></script>
<script src="{{url_for('static', filename='js/vendor/aos.js')}}" type="text/javascript"></script>
<script src="{{url_for('static', filename='js/socket.io.js')}}" type="text/javascript"></script>
<noscript>
<style>
*[data-aos] {
display: block !important;
opacity: 1 !important;
visibility: visible !important;
}
</style>
</noscript>
<script>
AOS.init({
duration: 700,
disable: function () {
var maxWidth = 1200;
return window.innerWidth < maxWidth;
}
});
/*
開啟服務,獲取分類運行結(jié)果
*/
var line_number = 1;
var socket = io();
// 專門接收后端推送消息
socket.on('service_msg', function(data) {
var row = "<tr>" +
"<th scope=\"row\">" + line_number + "</th>" +
"<td align=\"left\">" + data.time + "</td>" +
"<td align=\"left\">" + data.msg + "</td>" +
"</tr>";
line_number++;
//添加數(shù)據(jù)到 table 第一行
$("#tbl_log tbody").prepend(row);
});
/*
運行服務,開始接收推送消息
*/
function run_serivce() {
$("#btn_running_state").attr("onclick", "pause_service()");
$("#i_running_state_icon").attr("class", "fas fa-pause");
$("#b_running_state_text").html("暫停服務");
var row = "<tr align=\"center\" class=\"text-success\"><th scope=\"row\" colspan=\"3\">啟動成功,開始接收數(shù)據(jù) ...</th></tr>"
$("#tbl_log tbody").prepend(row);
$.ajax({
type: "get", // 請求方式
url: "start_service", // 請求路徑
async: true, // 異步請求
dataType: "json", // 預期返回一個 json 類型數(shù)據(jù)
success: function (data) { // data是形參名,代表返回的數(shù)據(jù)
console.log(data);
}
});
}
/*
暫停服務
*/
function pause_service() {
$("#btn_running_state").attr("onclick", "run_serivce()");
$("#i_running_state_icon").attr("class", "fas fa-play");
$("#b_running_state_text").html("啟動服務");
var row = "<tr align=\"center\" class=\"text-secondary\"><th scope=\"row\" colspan=\"3\">服務暫停,等待開啟 ...</th></tr>"
$("#tbl_log tbody").prepend(row);
$.ajax({
type: "get", // 請求方式
url: "stop_service", // 請求路徑
async: true, // 異步請求
dataType: "json", // 預期返回一個 json 類型數(shù)據(jù)
success: function (data) { // data是形參名,代表返回的數(shù)據(jù)
console.log(data);
}
});
}
</script>
</body>
</html>
運行步驟
cmd 或者 linux控制臺運行即可
python app.py
此時能看到如下圖所示
此時訪問http://0.0.0.0:5200(0.0.0.0 替換成對應IP或者127.0.0.1或localhost即可看到圖1-3效果)
代碼理解
在python代碼中,首先通過SocketIO封裝flask app
socketio = SocketIO(app, cors_allowed_origins="*")
通過cors_allowed_origins="*"
來指定支持跨域訪問限制問題
另外設(shè)定全局變量service_state = 0
用來控制服務運行狀態(tài),從而根據(jù)結(jié)果是否要向前端發(fā)送數(shù)據(jù)。
最后就是在啟動接口/start_service
上增加狀態(tài)判斷死循環(huán),只要service_state = 0
,就會不斷向前端發(fā)送數(shù)據(jù)(我這加了2秒間歇),具體方法調(diào)用前面定義的socketio
變量的emit
函數(shù)即可,如下所示:
socketio.emit("service_msg", json_data)
而要停止推送服務的話,那只需要調(diào)用/stop_service
改變?nèi)肿兞?code>service_state的值即可。文章來源:http://www.zghlxwxcb.cn/news/detail-542470.html
代碼下載
【GitCode地址:flask_socketio_quickstart】文章來源地址http://www.zghlxwxcb.cn/news/detail-542470.html
到了這里,關(guān)于【快速開始】一個簡單的Flask-SocketIO應用,完成后端推送消息接收與關(guān)閉的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!