1.hello world
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
当用户打开默认网页时会调用hello world方法里面的内容。
@app.route('/about')
def about():
return 'About page'
浏览器中访问 http://127.0.0.1:5000/about,你将看到显示 "About page" 的新页面。
2.线程
定义一个线程函数
def background_task():
print("开始执行后台任务")
# 模拟耗时操作
import time
time.sleep(10)
print("后台任务完成")
在flask框架中启动这个线程
app = Flask(__name__)
@app.route('/start-task')
def start_task():
thread = threading.Thread(target=background_task)
thread.start()
return '后台任务已开始执行'
3.使用 WebSocket实时传输后端数据到前端并更新
from flask import Flask
from flask_socketio import SocketIO, emit
import threading
app = Flask(__name__)
socketio = SocketIO(app)
def background_task():
# 模拟耗时操作
import time
time.sleep(10)
socketio.emit('task_complete', {'data': '任务完成'})
@app.route('/start-websocket-task')
def start_websocket_task():
thread = threading.Thread(target=background_task)
thread.start()
return 'WebSocket后台任务已开始'
@socketio.on('connect')
def test_connect():
emit('my_response', {'data': '已连接'})
if __name__ == '__main__':
socketio.run(app, debug=True)
当前后端连接成功后会调用test_connect()函数,之后在后端每过一秒向前端发送一个数据包,前端解析并显示数据:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebSocket 计数器</title>
<script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on('my_response', function(msg) {
console.log(msg.data);
});
socket.on('count_update', function(msg) {
document.getElementById('count').innerHTML = msg.count;
});
});
</script>
</head>
<body>
<h1>WebSocket 计数器</h1>
<div>当前计数:<span id="count">0</span></div>
</body>
</html>
其中这一段代码
socket.on('count_update', function(msg) {
document.getElementById('count').innerHTML = msg.count;
});
设置了一个事件监听器,当从服务器接收到名为 'count_update'
的事件时,执行一个回调函数。该函数更新 HTML 文档中 ID 为 'count'
的元素的内容,使其显示从服务器发送的计数 (msg.count
)。
4.前端显示图片
1) 将图片文件放置在服务器的某个可以公开访问的目录中,通常是静态文件目录;2) 在网页中通过 URL 引用这个图片。
<img src="{{ url_for('static', filename='images/my-image.jpg') }}" alt="描述性文字">
5.后端动态修改前端显示图片
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
import threading
import time
app = Flask(__name__)
socketio = SocketIO(app)
@app.route('/')
def index():
return render_template('index.html')
def update_image_and_notify():
# 模拟长时间的操作
print("开始后台处理...")
time.sleep(10) # 假设这是一个耗时10秒的操作
# 假设现在图片已更新
print("后台处理完成,图片已更新")
# 通知前端重新加载图片
socketio.emit('update_image', {'url': '/static/images/updated_image.jpg'})
@app.route('/start-update')
def start_update():
thread = threading.Thread(target=update_image_and_notify)
thread.daemon = True
thread.start()
return "后台图片更新已启动"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Image Update Notification</title>
<script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on('update_image', function(data) {
console.log("Received update notification.");
var img = document.getElementById('dynamicImage');
img.src = data.url + "?t=" + new Date().getTime(); // 添加时间戳以防缓存
});
});
</script>
</head>
<body>
<h1>Dynamic Image Reload</h1>
<img id="dynamicImage" src="/static/images/initial_image.jpg" alt="Dynamic Image">
</body>
</html>
通过这种方法,后台线程在完成操作更新图片后,会实时通知前端进行图片的重新加载。这种实时通信确保用户总是看到最新的内容,无需手动刷新页面。