opencv 如何在ASGI中使用StreamingHttpResponse运行Django通道

e3bfsja2  于 2022-11-30  发布在  Go
关注(0)|答案(1)|浏览(194)

bounty将在2天后过期。回答此问题可获得+50声望奖励。Simone Pozzoli希望吸引更多人关注此问题。

我有一个简单的应用程序,它使用开放的cv和设置在wsgi中的服务器来流式传输图像。但是每当我将Django频道引入图片并从WSGI更改为ASGI时,流式传输就会停止。我如何在使用Django channels的同时从cv2流式传输图像?提前感谢您
我的流媒体代码:

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))
})
sqyvllje

sqyvllje1#

首先,我们根本不需要StrammingHTTPResponse来发送图像数据...
为此,首先,确保你有一个Django 3.x和Python 3.7+的版本。
然后,安装django-channels第三方软件包。
按如下所示配置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
        )
    )
})

然后,您需要在www.example.com文件中设置ASGI_APPLICATION常量settings.py:

ASGI_APPLICATION = "myproject.asgi.application"

之后,只需在应用程序中的www.example.com文件中创建一个异步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,
        }))

也为asyncwebsocket使用者创建一个路由...

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

相关问题