就是現在我想先簡單用一個flask網頁試試看說我按下一頁後,就會跳轉到另一個網頁,但是一直出現
而我的vscode出現此錯誤:werkzeug.routing.exceptions.BuildError: Could not build url for endpoint 'video_feed'. Did you mean 'index' instead?
要按下一頁的地方:first.py & first.html
from flask import Flask, render_template, redirect, url_for
app = Flask(__name__)
@app.route('/')
def index():
return render_template('first.html')
@app.route('/next_page', methods=['POST'])
def next_page():
return redirect(url_for('home'))
@app.route('/home')
def home():
return render_template('home.html')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
<!DOCTYPE html>
<html>
<head>
<title>推薦購物網</title>
</head>
<body>
<h1>買買</h1>
<form action="{{ url_for('next_page') }}" method="post">
<button type="submit">下一頁</button>
</form>
</body>
</html>
我要跳轉到的地方:app.py & home.html
from flask import Flask, render_template, Response
import cv2
import numpy as np
import torch
import time
import webbrowser
app = Flask(__name__)
model = torch.hub.load('ultralytics/yolov5', 'custom', path='best.pt', force_reload=True)
cap = cv2.VideoCapture(0)
height, width, _ = cap.read()[1].shape
opened_links = []
def detect_objects():
while cap.isOpened() and not video_started:
time.sleep(0.1)
while cap.isOpened():
success, frame = cap.read()
if not success:
print("Ignoring empty camera frame.")
continue
frame = cv2.resize(frame, (800, 480))
results = model(frame)
detected_objects = results.xyxy[0]
for obj in detected_objects:
obj_class = int(obj[-1])
if obj_class in [0, 1, 2]:
link_url = ""
if obj_class == 0:
link_url = "https://online.carrefour.com.tw/zh/%E5%85%89%E6%B3%89/1003400300106.html"
elif obj_class == 1:
link_url = "https://online.carrefour.com.tw/zh/%E7%A6%8F%E6%A8%82/1502200500124.html"
elif obj_class == 2:
link_url = "https://ecshweb.pchome.com.tw/search/v3.3/?q=%E7%BE%8E%E7%A5%BF"
if link_url not in opened_links:
webbrowser.open(link_url)
opened_links.append(link_url)
time.sleep(3)
break
img_bytes = cv2.imencode('.jpg', np.squeeze(results.render()))[1].tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + img_bytes + b'\r\n')
@app.route('/')
def index():
return render_template('home.html')
@app.route('/start_video', methods=['POST'])
def start_video():
global video_started
video_started = True
return '已啟動'
@app.route('/video_feed')
def video_feed():
return Response(detect_objects(), mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
<!doctype html>
<html>
<head>
<title>哭哭</title>
</head>
<body>
<h1>人生好難</h1>
<button onclick="startDetection()" type="button">開始掃描</button>
<img id="videoStream" width="800" height="480">
<script>
function startDetection() {
fetch('/start_video', {
method: 'POST'
})
.then(response => {
if (response.ok) {
console.log('已啟動');
document.getElementById('videoStream').src = "{{ url_for('video_feed') }}";
} else {
console.log('無法啟動');
}
})
.catch(error => console.log(error));
}
</script>
</body>
</html>
再麻煩各位了
你應該要把你的 router 都放在同一個檔案中
from flask import Flask, render_template, redirect, url_for, Response
import cv2
import numpy as np
import torch
import time
import webbrowser
model = torch.hub.load('ultralytics/yolov5', 'custom', path='best.pt', force_reload=True)
cap = cv2.VideoCapture(0)
height, width, _ = cap.read()[1].shape
opened_links = []
def detect_objects():
while cap.isOpened() and not video_started:
time.sleep(0.1)
.....
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + img_bytes + b'\r\n')
app = Flask(__name__)
@app.route('/')
def index():
return render_template('first.html')
@app.route('/next_page', methods=['POST'])
def next_page():
return redirect(url_for('home'))
@app.route('/home')
def home():
return render_template('home.html')
@app.route('/')
def index():
return render_template('home.html')
@app.route('/start_video', methods=['POST'])
def start_video():
global video_started
video_started = True
return '已啟動'
@app.route('/video_feed')
def video_feed():
return Response(detect_objects(), mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
如果要拆成兩個檔案應該使用Blueprints
first.py
from flask import Blueprint, render_template, redirect, url_for
app = Blueprint("first", __name__)
...
first.html
<!DOCTYPE html>
<html>
<head>
<title>推薦購物網</title>
</head>
<body>
<h1>買買</h1>
<form action="{{ url_for('first.next_page') }}" method="post">
<button type="submit">下一頁</button>
</form>
</body>
</html>
app.py
from first import app as firstapp
app = Flask(__name__)
app.register_blueprint(firstapp)
...