我正在按照文档站点中的说明进行操作,但我遇到了echo示例,websocket已正确创建并且已连接到服务器但是当我向服务器发送任何内容时,我没有得到任何响应(在示例中)说我应该看到一个警告窗口,其中包含我发送到套接字的相同消息,但我没有,虽然我已经更改了console.log的警报,但仍然),我做错了什么?
在settings.py中:
INSTALLED_APPS = {
...
'channels',
'myapp',
...
}
...
# Channels settings
CHANNEL_LAYERS = {
"default": {
"BACKEND": "asgiref.inmemory.ChannelLayer",
"ROUTING": "myapp.routing.channel_routing",
},
}
Run Code Online (Sandbox Code Playgroud)
在routing.py中:
from channels.routing import route
from myapp.consumers import *
channel_routing = [
route("websocket.receive", ws_receive),
]
Run Code Online (Sandbox Code Playgroud)
在consumers.py中:
def ws_receive(message):
# ASGI WebSocket packet-received and send-packet message types
# both have a "text" key for their textual data.
message.reply_channel.send({
"text": message.content['text'],
})
Run Code Online (Sandbox Code Playgroud)
在asgi.py
import os
from channels.asgi import get_channel_layer …
Run Code Online (Sandbox Code Playgroud) 我的技术堆栈是Redis作为通道后端,Postgresql作为数据库,Daphne作为ASGI服务器,Nginx作为整个应用程序.使用Docker Swarm部署所有内容,只有Redis和数据库外部.我有大约20个虚拟主机,20个接口服务器,40个http工作者和20个websocket工作者.使用Ingress覆盖Docker网络完成负载平衡.
问题是,有时在性能上会发生非常奇怪的事情.大多数请求的处理时间不到400毫秒,但有时请求可能需要2-3秒,即使在非常小的负载下也是如此.使用Django调试工具栏或基于中间件的分析器的分析工作程序什么都不显示(时间0.01s左右)
我的问题:有什么好方法可以用django-channels分析整个请求路径吗?我希望每个阶段花费多少时间,即当Daphne处理请求时,当工作者开始处理时,当它完成时,当接口服务器向客户端发送响应时.目前,我不知道如何解决这个问题.
我发现大多数关于Django频道的文档都是关于WebSockets的.但我想以不同的方式使用它们,我相信它是可能的.
如何使用Django通道运行异步定期任务?例如,我想每15秒检查一些网站上的温度(通过API),当它达到> 20时我需要通知.
这也意味着这项任务将持续很长时间(甚至可能持续3个月),Django能否让消费者长期生活?
谢谢.
通常,在Django中使用ASGI代替WSGI进行HTTP请求的明显和明显的缺点是什么?
我知道ASGI用于异步任务,但它也可以通过http.*
通道处理同步HTTP请求。它比普通的WSGI慢吗?还是与WSGI相比有不受支持的功能?
另外,要在同一项目中同时提供REST API和websocket处理,您更喜欢哪种方式,为什么呢?
我第一次尝试使用 django 频道,我正在按照文档中的教程进行操作。但是当我使用 python manage.py runserver 并尝试连接时,我收到此错误。
Protocol error, got "H" as reply type byte
Run Code Online (Sandbox Code Playgroud)
这是整个控制台(我正在使用 anaconda):
Quit the server with CTRL-BREAK.
2018-06-20 15:59:25,665 - INFO - server - HTTP/2 support not enabled (install the http2 and tls Twisted extras)
2018-06-20 15:59:25,665 - INFO - server - Configuring endpoint tcp:port=8000:interface=127.0.0.1
2018-06-20 15:59:25,665 - INFO - server - Listening on TCP address 127.0.0.1:8000
[2018/06/20 15:59:36] HTTP GET /chat/lobby/ 200 [0.12, 127.0.0.1:62590]
[2018/06/20 15:59:36] WebSocket HANDSHAKING /ws/chat/lobby/ [127.0.0.1:62594]
2018-06-20 15:59:37,694 - ERROR …
Run Code Online (Sandbox Code Playgroud) 我正在开发一个需要特定信令服务器实现的WebRTC应用程序.最初我在NodeJS中开发服务器但后来我决定迁移到Python(使用Django Channels AsyncWebsocketConsumer通过Websockets与客户端通信).迁移后,我使用WebSocket基准测试工具Thor来比较两种实现,这些是获得的结果(5000个websocket连接,每个连接发送1000条消息):
Python(Django Channels)实现:
class SignallingConsumer(AsyncWebsocketConsumer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.peer = None
self.signal = None
self.is_peer_registered = False
async def connect(self):
await self.accept()
async def disconnect(self, close_code):
pass
async def receive(self, text_data=None, bytes_data=None):
pass
Run Code Online (Sandbox Code Playgroud)
NodeJS实现:
method.start = function () {
this.webServer = this.createWebServer();
this.webServer.listen(this.config.port, function (){
console.log("Web server is listening");
});
this.socket = this.createWebSocket(this.webServer);
this.socket.on('connection', function(ws) {
var pingsCompleted = 0;
ws.on('message', function(evt) {
}.bind(this));
// Set out ping/pong mechanism
var pingInterval = setInterval(function() {
if(pingsCompleted …
Run Code Online (Sandbox Code Playgroud) 我正在 Django 中制作一个 Chatapp 项目。我实现了通道和 websockets 来发送和接收消息,当我在同一浏览器中使用两个不同的窗口(其中一个处于隐身模式)进行测试时,这是有效的,但是当我尝试使用另一个浏览器测试它时,我收到以下错误:
我尝试使用以下配置解决实现 django corsheaders 的问题:
(我知道将所有起源设置为 true 并不推荐,但这只是为了测试目的)
我已经安装了Django-Channels但是在运行daphne-server时我得到的错误如下:
File "/usr/local/lib/python2.7/dist-packages/channels/asgi.py", line 36, in make_backend
"Cannot import BACKEND %r specified for %s" % (self.configs[name]['BACKEND'], name)
channels.asgi.InvalidChannelLayerError: Cannot import BACKEND 'asgi_redis.RedisChannelLayer' specified for default
Run Code Online (Sandbox Code Playgroud)
我的settings.py是:
CHANNEL_LAYERS = {
"default": {
"BACKEND": "asgi_redis.RedisChannelLayer",
"CONFIG": {
"hosts": [os.environ.get('REDIS_URL', 'redis://X.X.X.X:6379')],
},
"ROUTING": "MyProject.routing.channel_routing",
},
}
Run Code Online (Sandbox Code Playgroud)
需要帮助来解决此错误.
我正在尝试开发一种拍卖类型系统,其中客户下订单,然后不同的商店可以为该订单提供价格.
该系统的一个有趣的部分是,当最初创建订单时,可用的商店将有60秒来提供他们各自的报价.当第一家商店提出要约时,"拍卖"现在只有接下来的20秒才能让其他商店自己出价.如果他们确实提出了另一个报价,在这个较小的分配时间内,那么这20秒就会刷新.只要有足够的时间,优惠可以继续收到,不能超过给定的最初60秒.
class Order(models.Model):
customer = models.ForeignKey(Customer)
create_time = models.DateTimeField(auto_now_add=True)
update_time = models.DateTimeField(auto_now_add=True)
total = models.FloatField(default=0)
status = models.IntegerField(default=0)
delivery_address = models.ForeignKey(DeliveryAddress)
store = models.ForeignKey(Store, null=True, blank=True, related_name='orders', on_delete=models.CASCADE)
credit_card = models.ForeignKey(CreditCard, null=True, blank=True, related_name='orders')
class OrderOffer(models.Model):
store = models.ForeignKey(Store, related_name="offers", on_delete=models.CASCADE)
order = models.ForeignKey(Order, related_name="offers", on_delete=models.CASCADE)
create_time = models.DateTimeField(auto_now_add=True)
Run Code Online (Sandbox Code Playgroud)
除了这些要求之外,我还想在新的优惠实时到达时更新客户.为此,我正在使用django-channels
WebSockets的实现.
我有以下consumers.py
文件:
from channels.generic.websockets import WebsocketConsumer
from threading import Timer
from api.models import Order, OrderOffer
from django.db.models.signals import post_save
from django.dispatch import receiver
class OrderConsumer(WebsocketConsumer):
def …
Run Code Online (Sandbox Code Playgroud) 我已Django Channels 2.1.2
按照教程在Django应用程序中进行了设置,现在需要为新消息设置通知系统。我想以最简单的方式做到这一点。
我可以通过浏览器推送通知来执行此操作,但是我不想那样做。我希望它像Stack Overflow,其中有一个红色的数字代表新消息的实例。
这里的一个答案说
对于通知,您仅需要两个模型:
User
和Notification
。在连接时,将范围设置为当前经过身份验证的用户。post_save
在Notification
模型上设置一个 信号,以触发使用方方法向通知对象的用户发送消息。–
我正在竭尽全力去寻找什么样的样子,我已经有了一个User
模型,但是没有Notification
人。
聊天仅在2个用户之间进行,它不是聊天室,而是更多的聊天线程。2个html模板是inbox.html
和thread.html
感谢任何帮助!
我的Django频道代码如下!
users.py
class ChatConsumer(AsyncConsumer):
async def websocket_connect(self, event):
print('connected', event)
other_user = self.scope['url_route']['kwargs']['username']
me = self.scope['user']
#print(other_user, me)
thread_obj = await self.get_thread(me, other_user)
self.thread_obj = thread_obj
chat_room = f"thread_{thread_obj.id}"
self.chat_room = chat_room
# below creates the chatroom
await self.channel_layer.group_add(
chat_room,
self.channel_name
)
await self.send({
"type": "websocket.accept"
})
async def websocket_receive(self, event):
# …
Run Code Online (Sandbox Code Playgroud) django ×10
django-channels ×10
python ×8
asynchronous ×1
daphne ×1
django-views ×1
javascript ×1
node.js ×1
profiling ×1
redis ×1
webrtc ×1
websocket ×1