我有一个简单的应用程序,它使用开放的cv和wsgi中的服务器来流图像。但是每当我将Django频道介绍到图片中,并从WSGI切换到ASGI时,流就停止了。我如何从cv2中流图像,同时使用Django channels?先谢谢你
我的流媒体代码:
def camera_feed(request):
stream = CameraStream()
frames = stream.get_frames()
return StreamingHttpResponse(frames, content_type='multipart/x-mixed-replace; boundary=frame')settings.py:
ASGI_APPLICATION = 'photon.asgi.application'asgi.py
application = ProtocolTypeRouter({
'http': get_asgi_application(),
'websocket': AuthMiddlewareStack(URLRouter(ws_urlpatterns))
})发布于 2022-11-28 13:26:04
首先,我们根本不需要StramingHTTPResponse发送图像数据.
为此,首先,确保您有一个包含3.x和Python的Django版本。
然后,安装django-频道第三方包。
按照以下方式配置ASGI应用程序:
import os
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
import .routing
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
app.routing.websocket_urlpatterns
)
)
})然后需要在ASGI_APPLICATION文件中设置settings.py常量:
ASGI_APPLICATION = "myproject.asgi.application"之后,只需在应用程序中的WebSocket文件中创建异步consumers.py使用者:
import json
from channels.generic.websocket import AsyncWebsocketConsumer
class PairingChat(AsyncWebsocketConsumer):
async def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = 'chat_%s' % self.room_name
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
async def disconnect(self):
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
# Asyncwebsocket consumer can send any type of data ...
async def receive(self, text_data):
data_json = json.loads(your_data)
message = data_json['message']
await self.channel_layer.group_send(
self.room_group_name,
{
'type': '# send your data from here ...',
'message': message,
'user': self.scope['session']['name']
}
)
async def chat_message(self, event):
message = event['message']
await self.send(data=json.dumps({
'user': event['user'],
'message': message,
}))为异步well使用者创建一个路由.
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r'ws/chat1/(?P<room_name>\w+)/$', consumers.PairingChat.as_asgi()),
]然后,只需在javascript中创建一个WebSocket客户机.你可以走了..。
JS Websocket创建链接:javascript-websocket
https://stackoverflow.com/questions/67876456
复制相似问题