我正在尝试使用
channels
来处理一些与 WebSockets 相关的内容,但当我重新加载网页时,它会不断加载并且不显示任何流响应。这是我的代码,在此设置下运行良好:
# settings.py
# WSGI_APPLICATION = 'main.wsgi.application' # work fine
ASGI_APPLICATION = "main.asgi.application" # not working
这是我的
views.py
:
@gzip.gzip_page # for performance
def video_stream(request: HttpRequest):
video = VideoContainer.objects.last()
video_path = video.file.path
return StreamingHttpResponse(generate_frames(VideoCamera(video_path)),
content_type="multipart/x-mixed-replace;boundary=frame")
这是我的
generate_frames
和 VideoCamera
的代码:
import cv2
class VideoCamera:
def __init__(self, video_path: str):
self.video = cv2.VideoCapture(video_path)
def __del__(self):
self.video.release()
def get_frame(self):
while (self.video.isOpened()):
img = self.video.read()[1]
# because web-page looking for image/jpeg content type
jpeg = cv2.imencode(".jpg", img)[1]
return jpeg.tobytes() # we stream it in byte form for frontend
def generate_frames(camera) -> bytes:
while True:
frame = camera.get_frame()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
我也遇到过类似的问题。我最终在不同的端口上为我的应用程序运行 WSGI 和 ASGI。 Gunicorn 在端口 8000 上运行,使用 WSGI 处理所有使用 StreamingHttpResponse 的 http 请求,而 Daphne 在端口 8001 上运行,使用 ASGI 处理所有与通道相关的内容。
gunicorn my_project.wsgi:application --bind 0.0.0.0:8000 --workers 4 --daemon
daphne -p 8001 my_project.asgi:application