django - StreamingHttpResponse 不适用于 ASGI,但可以正常使用 WSGI
问题描述
我正在尝试使用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')
解决方案
推荐阅读
- powershell - 用于获取自上次写入文件以来的分钟数的 Powershell 函数
- dns - 如何使用 Pulumi 管理 Openstack 上的 DNS 记录?
- javascript - 由于不活动消息,Iframe URL 发布请求页面已过期
- regex - 普罗米修斯警报名称正则表达式
- python - 是否有可能的替代方法(代码)来重塑当前正在使用融化功能进行重塑的给定熊猫数据框?
- visual-studio - 如何从 cmake 将构建后命令设置为 VS 项目?
- sql - 汇总列以获得一个值
- node.js - Express 和 WebSocket 在同一个端口上
- java - 从 7.2 移植后的 Liferay 7.3 java.lang.NullPointerException
- swift - 音频播放按钮 - 开始、停止