首先,我们根本不需要使用StramingHTTPResponse来发送图像数据...
为此,首先确保您拥有3.x版本的Django和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
)
)
})
然后,您需要在settings.py文件中设置ASGI_APPLICATION常量:
ASGI_APPLICATION = "myproject.asgi.application"
之后,只需在应用程序的consumer.py文件中创建一个异步 WebSocket 消费者:
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
)
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,
}))
创建一个异步websocket消费者的路由,如下所示:
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