如何从命令向通道发送消息

时间:2017-03-08 04:02:10

标签: python django django-channels

如何从自定义manage.py命令向Django Consumer发送消息

from django.core.management.base import BaseCommand, CommandError
from channels import Channel

class Command(BaseCommand):
   help = 'Sends a message to a Django channel from the thing'

   def add_arguments(self, parser):
       parser.add_argument('json_object', nargs='+', type=str)

   def handle(self, *args, **options):
       self.stdout.write("TEST !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")


       print Channel("test").channel_layer
       Channel("test").send({'op':options['json_object'][0]})

这是我的消费者

class MyConsumer(WebsocketConsumer):

   @classmethod
   def channel_names(self):
      return {"test"}

   def connection_groups(self):
      return ["test"]

   def dispatch(self, message, **kwargs):
      return self.get_handler(message, **kwargs)(message, **kwargs)

  def get_handler(self, message, **kwargs):
          channel_routing = [
    consumers.MyConsumer.as_route(path=r"^/test/"),
    route("test.receive", consumers.chat_join),
]         for _filter, value in kwargs.items():
        filter_mapping = getattr(self, _filter + '_mapping', None)
        if not filter_mapping:
            continue

        consumer = getattr(self, filter_mapping.get(value), None)
        if consumer:
            return consumer
     raise ValueError('Message')


  def connect(self,message):
    self.message.reply_channel.send({"accept": True})

  def receive(self,text=None, bytes= None):
    print text

  def disconnect(self,message):
    pass

当我尝试运行该命令时,我收到此消息

  

2017-03-08 03:45:33,839 - ERROR - worker - 无法找到测试消息的匹配项!检查您的路由。

如果它是相关的,这是我的路由

channel_routing = [
    consumers.MyConsumer.as_route(path=r"^/test/"),
]         

1 个答案:

答案 0 :(得分:1)

简而言之,将export class HomePage { tables: any[] //... addTable(){ let prompt = this.alertCtrl.create({ title: 'Add Table', subTitle: 'Enter the table number', inputs: [{ name: 'tableNumber', placeholder: 'Number', type: 'number' }], buttons: [ { text: 'Cancel' }, { text: 'Add', handler: data => { let table = { number: data.tableNumber, name: 'occupied' } alert('Success'); this.tables.push(table); } } ] }); } 添加到您要发送的path

content

那就是它!

我遇到了同样的问题,我发现这是因为我使用通用消费者的Channel("test").send({ 'op':options['json_object'][0], 'path': '/test/', }) 方法来生成as_route,它始终以route_class作为其过滤器。

如果我们使用path代替我们,则不一定提供route参数,以及doc(https://channels.readthedocs.io/en/stable/getting-started.html#models)代码的工作原理