【问题标题】:How to redirect from StreamingHttpResponse in Django如何从 Django 中的 StreamingHttpResponse 重定向
【发布时间】:2021-10-21 16:12:22
【问题描述】:

我想实现这个流程:

  1. 主页中的网络摄像头检测到用户的面部
  2. 该应用获取用户的考勤,显示一个包含考勤详情的网页
  3. 在网络摄像头仍在运行的情况下,出勤详情页面将在几秒钟后重定向回主页

到目前为止,我的应用可以获取用户的出勤情况,但即使我使用了 return render(),也不会呈现到出勤详情页面。它将保留在主页上,网络摄像头仍在运行。有没有办法可以解决这个问题,或者我有什么问题?我曾尝试像这样手动更改请求详细信息,但它不起作用。

request.resolver_match = resolve('/takeAttendance/')
        request.path='/takeAttendance/'
        request.path_info='/takeAttendance/'

类似于How to redirect to another url after detect face in django 的问题,但没有一个答案对我有用。 涉及代码如下:

views.py

from django.shortcuts import render, redirect
from django.contrib import messages
from django.http import HttpResponse , StreamingHttpResponse
from datetime import datetime, date
import cv2
import face_recognition
import numpy as np
import threading

foundFace = False
vs = cv2.videoCapture(0)
lock = threading.Lock()
frame = None

def videoFeed(request):
        return StreamingHttpResponse(getFace(request),content_type="multipart/x-mixed-replace;boundary=frame")

def getFace(request):
    global vs,outputFrame,lock,foundFace
    known_face_names,known_face_encodings = getFiles() # get the image files from my project directory
    face_location = []
    face_encoding = []
    while foundFace==False:
        check,frame = vs.read()
        small_frame = cv2.resize(frame,(0,0),fx=0.5,fy=0.5)
        face_roi = small_frame[:,:,::-1]
        face_location = face_recognition.face_locations(face_roi)
        face_encoding = face_recognition.face_encodings(face_roi,face_location)
        face_names = []
        names=[]
        for encoding in face_encoding:
            matches = face_recognition.compare_faces(known_face_encodings,np.array(encoding),tolerance=0.6)
            distances = face_recognition.face_distance(known_face_encodings,encoding)
            matches = face_recognition.compare_faces(known_face_encodings,np.array(encoding),tolerance=0.6)
            distances = face_recognition.face_distance(known_face_encodings,encoding)
            best_match_index = np.argmin(distances) 

            if matches[best_match_index]:
                name = known_face_names[best_match_index]
                face_names.append(name)
                if name not in names:
                    names.append(name)
        #process the frame (add text and rectangle, add the name of the identified user to names)
        with lock:
            (flag,encodedImg) = cv2.imencode(".jpg",frame)
            
        if len(names)!=0:
            foundFace=True
        if foundFace==True:
            takeAttendance(request,names)
            foundFace==False
        yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + 
            bytearray(encodedImg) + b'\r\n')

def takeAttendance(request,names):
    context={}
    if request.method=='GET':
        if user_id in names:
            attendance = Attendance(user_ID = str(user_id),
                                            date_in = date.today(),
                                            time_in = datetime.now())
            attendance.save()
            context={'attendance':attendance}
            messages.success(request,'Check in successful')
            return render(request,'Attendance/attendance.html',context)
        else:
            messages.error(request,'Check in failed')
            return redirect('home')
    else:
        return redirect('home')

urls.py

from django.urls import path
from . import views
urlpatterns=[
    path('home/',views.home,name='home'),
    path('takeAttendance/',views.takeAttendance,name='takeAttendance'),
    path('videoFeed/',views.videoFeed,name='videoFeed'),

]

我正在使用 Django 3.1,我对它很陌生,谢谢!

编辑

实际上,我想重定向到Attendance.html,但保持视频流运行,就像循环一样,这样我就可以使用 JavascriptAttendance.html 重定向到网络摄像头页面,并且仍然有视频流运行。抱歉没有说清楚。

【问题讨论】:

  • 我可以看到attendance.html 应该在面部检查通过后返回。发生了吗?
  • @rzlvmp 这正是我想要的。但是,它仍然与网络摄像头保持在同一页面上,并且不会重定向到attendance.html。这就是我感到困惑的原因。

标签: python django opencv


【解决方案1】:

哦...为什么我没有注意到...

问题是:

...
        if foundFace==True:
            takeAttendance(request,names)
...

是的,您在getFace 中执行返回渲染输出的函数。就是这样,getFace 根本不使用返回值。

正确的代码应该是这样的:

...
        if foundFace==True:
            returned_render = takeAttendance(request,names)
            return returned_render
...

或者简单地说:

...
        if foundFace==True:
            return takeAttendance(request,names)
            # or maybe you should use yield instead of return?
            # I don't know. Check both
            yield takeAttendance(request,names)
...

【讨论】:

  • 所以我尝试了return,但它会停止视频流,即使我尝试刷新页面也是如此。有没有办法让我可以return 它但我的视频流仍在运行?几秒钟后,我将使用 Javascript 重定向回带有来自 Attendance.html 的网络摄像头流的页面。不,yield 没有奏效。谢谢你的回答。
猜你喜欢
  • 2013-12-31
  • 2013-02-13
  • 1970-01-01
  • 2013-02-27
  • 1970-01-01
  • 2016-06-09
  • 2013-05-10
相关资源
最近更新 更多