Exemplo n.º 1
0
def ws_receive(message):
    """Receive a message from a websocket.

    As of now, that message should be either 'ping' or the REST session token.
    """
    content = message.content['text']
    if content != "ping":
        content = json.loads(content)
        token = content['token']
        setup_logger("server").info("Registering client with token %r", token)
        CHANNEL_TO_TOKEN[message.reply_channel.name] = token
Exemplo n.º 2
0
 def handle(self, *args, **options):
     # Get the backend to use
     self.verbosity = options.get("verbosity", 1)
     self.logger = setup_logger('django.channels', self.verbosity)
     self.channel_layer = channel_layers[options.get("layer", DEFAULT_CHANNEL_LAYER)]
     # Check that handler isn't inmemory
     if self.channel_layer.local_only():
         raise CommandError(
             "You cannot span multiple processes with the in-memory layer. " +
             "Change your settings to use a cross-process channel layer."
         )
     # Check a handler is registered for http reqs
     # Serve static files if Django in debug mode
     if settings.DEBUG:
         self.channel_layer.router.check_default(http_consumer=StaticFilesConsumer())
     else:
         self.channel_layer.router.check_default()
     # Launch a worker
     self.logger.info("Running worker against channel layer %s", self.channel_layer)
     # Optionally provide an output callback
     callback = None
     if self.verbosity > 1:
         callback = self.consumer_called
     # Run the worker
     try:
         worker = Worker(
             channel_layer=self.channel_layer,
             callback=callback,
             only_channels=options.get("only_channels", None),
             exclude_channels=options.get("exclude_channels", None),
         )
         worker_ready.send(sender=worker)
         worker.run()
     except KeyboardInterrupt:
         pass
Exemplo n.º 3
0
 def handle(self, *args, **options):
     self.verbosity = options.get("verbosity", 1)
     self.logger = setup_logger('django.channels', self.verbosity)
     # Get the backend to use
     channel_backend = channel_backends[DEFAULT_CHANNEL_BACKEND]
     if channel_backend.local_only:
         raise CommandError(
             "You have a process-local channel backend configured, and so cannot run separate interface servers.\n"
             "Configure a network-based backend in CHANNEL_BACKENDS to use this command."
         )
     # Run the interface
     port = int(options.get("port", None) or 9000)
     try:
         import asyncio  # NOQA
     except ImportError:
         from channels.interfaces.websocket_twisted import WebsocketTwistedInterface
         self.logger.info("Running Twisted/Autobahn WebSocket interface server")
         self.logger.info(" Channel backend: %s", channel_backend)
         self.logger.info(" Listening on: ws://0.0.0.0:%i" % port)
         WebsocketTwistedInterface(channel_backend=channel_backend, port=port).run()
     else:
         from channels.interfaces.websocket_asyncio import WebsocketAsyncioInterface
         self.logger.info("Running asyncio/Autobahn WebSocket interface server")
         self.logger.info(" Channel backend: %s", channel_backend)
         self.logger.info(" Listening on: ws://0.0.0.0:%i", port)
         WebsocketAsyncioInterface(channel_backend=channel_backend, port=port).run()
Exemplo n.º 4
0
 def handle(self, *args, **options):
     self.verbosity = options.get('verbosity', 1)
     self.logger = setup_logger('django.channels', self.verbosity)
     self.honcho = OTreeHonchoManager()
     self.setup_honcho(options)
     self.honcho.loop()
     sys.exit(self.honcho.returncode)
Exemplo n.º 5
0
 def handle(self, *args, **options):
     self.verbosity = options.get("verbosity", 1)
     self.logger = setup_logger('django.channels', self.verbosity)
     self.http_timeout = options.get("http_timeout", 60)
     self.websocket_handshake_timeout = options.get(
         "websocket_handshake_timeout", 5)
     super(Command, self).handle(*args, **options)
Exemplo n.º 6
0
    def handle(self, *args, **options):
        # Get the backend to use
        self.verbosity = options.get("verbosity", 1)

        self.logger = setup_logger('django.channels', self.verbosity)
        self.channel_layer = channel_layers[options.get("layer", DEFAULT_CHANNEL_LAYER)]
        # Check that handler isn't inmemory
        if self.channel_layer.local_only():
            raise CommandError(
                "You cannot span multiple processes with the in-memory layer. " +
                "Change your settings to use a cross-process channel layer."
            )
        # Check a handler is registered for http reqs
        self.channel_layer.router.check_default()
        # Launch a worker
        self.logger.info("Running worker against channel layer %s", self.channel_layer)
        # Run the worker
        num_threads = options['num_threads']
        if num_threads == 1:
            Worker(channel_layer=self.channel_layer).run()
        else:
            worker_threads = []
            for _ in range(num_threads):
                worker = WorkerThread(self.channel_layer, self.logger)
                worker.daemon = True
                worker.start()
                worker_threads.append(worker)
            while True:
                time.sleep(5)
Exemplo n.º 7
0
 def handle(self, *args, **options):
     self.verbosity = options.get('verbosity', 1)
     self.logger = setup_logger('django.channels', self.verbosity)
     self.honcho = OTreeHonchoManager()
     self.setup_honcho(options)
     self.honcho.loop()
     sys.exit(self.honcho.returncode)
Exemplo n.º 8
0
 def handle(self, *args, **options):
     self.verbosity = options.get("verbosity", 1)
     self.logger = setup_logger('django.channels', self.verbosity)
     # Get the backend to use
     channel_backend = channel_backends[DEFAULT_CHANNEL_BACKEND]
     if channel_backend.local_only:
         raise CommandError(
             "You have a process-local channel backend configured, and so cannot run separate interface servers.\n"
             "Configure a network-based backend in CHANNEL_BACKENDS to use this command."
         )
     # Run the interface
     port = int(options.get("port", None) or 9000)
     try:
         import asyncio  # NOQA
     except ImportError:
         from channels.interfaces.websocket_twisted import WebsocketTwistedInterface
         self.logger.info(
             "Running Twisted/Autobahn WebSocket interface server")
         self.logger.info(" Channel backend: %s", channel_backend)
         self.logger.info(" Listening on: ws://0.0.0.0:%i" % port)
         WebsocketTwistedInterface(channel_backend=channel_backend,
                                   port=port).run()
     else:
         from channels.interfaces.websocket_asyncio import WebsocketAsyncioInterface
         self.logger.info(
             "Running asyncio/Autobahn WebSocket interface server")
         self.logger.info(" Channel backend: %s", channel_backend)
         self.logger.info(" Listening on: ws://0.0.0.0:%i", port)
         WebsocketAsyncioInterface(channel_backend=channel_backend,
                                   port=port).run()
Exemplo n.º 9
0
 def handle(self, *args, **options):
     # Get the backend to use
     self.verbosity = options.get("verbosity", 1)
     self.logger = setup_logger('django.channels', self.verbosity)
     channel_backend = channel_backends[DEFAULT_CHANNEL_BACKEND]
     if channel_backend.local_only:
         raise CommandError(
             "You have a process-local channel backend configured, and so cannot run separate workers.\n"
             "Configure a network-based backend in CHANNEL_BACKENDS to use this command."
         )
     # Check a handler is registered for http reqs
     if not channel_backend.registry.consumer_for_channel("http.request"):
         # Register the default one
         channel_backend.registry.add_consumer(UrlConsumer(),
                                               ["http.request"])
     # Launch a worker
     self.logger.info("Running worker against backend %s", channel_backend)
     # Optionally provide an output callback
     callback = None
     if self.verbosity > 1:
         callback = self.consumer_called
     # Run the worker
     try:
         Worker(channel_backend=channel_backend, callback=callback).run()
     except KeyboardInterrupt:
         pass
Exemplo n.º 10
0
 def handle(self, *args, **options):
     # Get the backend to use
     self.verbosity = options.get("verbosity", 1)
     self.logger = setup_logger('django.channels', self.verbosity)
     self.channel_layer = channel_layers[options.get(
         "layer", DEFAULT_CHANNEL_LAYER)]
     # Check that handler isn't inmemory
     if self.channel_layer.local_only():
         raise CommandError(
             "You cannot span multiple processes with the in-memory layer. "
             + "Change your settings to use a cross-process channel layer.")
     # Check a handler is registered for http reqs
     # Serve static files if Django in debug mode
     if settings.DEBUG:
         self.channel_layer.router.check_default(
             http_consumer=StaticFilesConsumer())
     else:
         self.channel_layer.router.check_default()
     # Launch a worker
     self.logger.info("Running worker against channel layer %s",
                      self.channel_layer)
     # Optionally provide an output callback
     callback = None
     if self.verbosity > 1:
         callback = self.consumer_called
     # Run the worker
     try:
         Worker(
             channel_layer=self.channel_layer,
             callback=callback,
             only_channels=options.get("only_channels", None),
             exclude_channels=options.get("exclude_channels", None),
         ).run()
     except KeyboardInterrupt:
         pass
Exemplo n.º 11
0
 def handle(self, *args, **options):
     # Get the backend to use
     self.verbosity = options.get("verbosity", 1)
     self.logger = setup_logger('django.channels', self.verbosity)
     channel_backend = channel_backends[DEFAULT_CHANNEL_BACKEND]
     if channel_backend.local_only:
         raise CommandError(
             "You have a process-local channel backend configured, and so cannot run separate workers.\n"
             "Configure a network-based backend in CHANNEL_BACKENDS to use this command."
         )
     # Check a handler is registered for http reqs
     if not channel_backend.registry.consumer_for_channel("http.request"):
         # Register the default one
         channel_backend.registry.add_consumer(UrlConsumer(), ["http.request"])
     # Launch a worker
     self.logger.info("Running worker against backend %s", channel_backend)
     # Optionally provide an output callback
     callback = None
     if self.verbosity > 1:
         callback = self.consumer_called
     # Run the worker
     try:
         Worker(channel_backend=channel_backend, callback=callback).run()
     except KeyboardInterrupt:
         pass
Exemplo n.º 12
0
 def handle(self, *args, **options):
     self.verbosity = options.get("verbosity", 1)
     self.logger = setup_logger("django.channels", self.verbosity)
     self.http_timeout = options.get("http_timeout", None)
     self.websocket_handshake_timeout = options.get("websocket_handshake_timeout", 5)
     # Check Channels is installed right
     if not hasattr(settings, "ASGI_APPLICATION"):
         raise CommandError("You have not set ASGI_APPLICATION, which is needed to run the server.")
     # Dispatch upward
     super().handle(*args, **options)
Exemplo n.º 13
0
def server(bind='127.0.0.1',
           port=8000,
           migrate_cmd=False,
           verbose=1):  # pragma: no cover
    try:
        from channels.log import setup_logger
        from channels.management.commands import runserver
        logger = setup_logger('django.channels', 1)
        use_channels = True
    except ImportError:
        from django.contrib.staticfiles.management.commands import runserver
        use_channels = False
        logger = None

    if os.environ.get('RUN_MAIN') != 'true':
        _create_db(migrate_cmd)
        User = get_user_model()
        if not User.objects.filter(is_superuser=True).exists():
            usr = create_user('admin',
                              '*****@*****.**',
                              'admin',
                              is_staff=True,
                              is_superuser=True)
            print('')
            print('A admin user (username: %s, password: admin) '
                  'has been created.' % usr.get_username())
            print('')
    rs = runserver.Command()
    try:
        from django.core.management.base import OutputWrapper
        rs.stdout = OutputWrapper(sys.stdout)
        rs.stderr = OutputWrapper(sys.stderr)
    except ImportError:
        rs.stdout = sys.stdout
        rs.stderr = sys.stderr
    rs.use_ipv6 = False
    rs._raw_ipv6 = False
    rs.addr = bind
    rs.port = port
    if logger:
        rs.logger = logger
    if use_channels:
        rs.http_timeout = 60
        rs.websocket_handshake_timeout = 5
    autoreload.main(
        rs.inner_run, (), {
            'addrport': '%s:%s' % (bind, port),
            'insecure_serving': True,
            'use_static_handler': True,
            'use_threading': True,
            'verbosity': verbose,
            'use_reloader': True
        })
Exemplo n.º 14
0
 def handle(self, *args, **options):
     self.verbosity = options.get("verbosity", 1)
     self.logger = setup_logger("django.channels", self.verbosity)
     self.http_timeout = options.get("http_timeout", 60)
     self.websocket_handshake_timeout = options.get(
         "websocket_handshake_timeout", 5)
     # Check Channels is installed right
     if not hasattr(settings, "ASGI_APPLICATION"):
         raise CommandError(
             "You have not set ASGI_APPLICATION, which is needed to run the server."
         )
     # Dispatch upward
     super().handle(*args, **options)
Exemplo n.º 15
0
 def handle(self,
            *args,
            addr=None,
            port=None,
            addrport=None,
            verbosity=1,
            **options):
     self.verbosity = verbosity
     self.logger = setup_logger('django.channels', self.verbosity)
     self.honcho = OTreeHonchoManager()
     self.setup_honcho(addr=addr, port=port, addrport=addrport)
     self.honcho.loop()
     sys.exit(self.honcho.returncode)
Exemplo n.º 16
0
 def handle(self, *args, **options):
     # Get the backend to use
     self.verbosity = options.get("verbosity", 1)
     self.logger = setup_logger('django.channels', self.verbosity)
     self.channel_layer = channel_layers[options.get(
         "layer", DEFAULT_CHANNEL_LAYER)]
     self.n_threads = options.get('threads', 1)
     # Check that handler isn't inmemory
     if self.channel_layer.local_only():
         raise CommandError(
             "You cannot span multiple processes with the in-memory layer. "
             + "Change your settings to use a cross-process channel layer.")
     # Check a handler is registered for http reqs
     # Serve static files if Django in debug mode
     if settings.DEBUG:
         self.channel_layer.router.check_default(
             http_consumer=StaticFilesConsumer())
     else:
         self.channel_layer.router.check_default()
     # Optionally provide an output callback
     callback = None
     if self.verbosity > 1:
         callback = self.consumer_called
     self.callback = callback
     self.options = options
     # Choose an appropriate worker.
     worker_kwargs = {}
     if self.n_threads == 1:
         self.logger.info("Using single-threaded worker.")
         worker_cls = Worker
     else:
         self.logger.info(
             "Using multi-threaded worker, {} thread(s).".format(
                 self.n_threads))
         worker_cls = WorkerGroup
         worker_kwargs['n_threads'] = self.n_threads
     # Run the worker
     self.logger.info("Running worker against channel layer %s",
                      self.channel_layer)
     try:
         worker = worker_cls(
             channel_layer=self.channel_layer,
             callback=self.callback,
             only_channels=self.options.get("only_channels", None),
             exclude_channels=self.options.get("exclude_channels", None),
             **worker_kwargs)
         worker_process_ready.send(sender=worker)
         worker.ready()
         worker.run()
     except KeyboardInterrupt:
         pass
Exemplo n.º 17
0
 def handle(self, *args, **options):
     # Get the backend to use
     self.verbosity = options.get("verbosity", 1)
     self.logger = setup_logger('django.channels', self.verbosity)
     self.channel_layer = channel_layers[options.get("layer", DEFAULT_CHANNEL_LAYER)]
     self.n_threads = options.get('threads', 1)
     # Check that handler isn't inmemory
     if self.channel_layer.local_only():
         raise CommandError(
             "You cannot span multiple processes with the in-memory layer. " +
             "Change your settings to use a cross-process channel layer."
         )
     # Check a handler is registered for http reqs
     # Serve static files if Django in debug mode
     if settings.DEBUG:
         self.channel_layer.router.check_default(http_consumer=StaticFilesConsumer())
     else:
         self.channel_layer.router.check_default()
     # Optionally provide an output callback
     callback = None
     if self.verbosity > 1:
         callback = self.consumer_called
     self.callback = callback
     self.options = options
     # Choose an appropriate worker.
     worker_kwargs = {}
     if self.n_threads == 1:
         self.logger.info("Using single-threaded worker.")
         worker_cls = Worker
     else:
         self.logger.info("Using multi-threaded worker, {} thread(s).".format(self.n_threads))
         worker_cls = WorkerGroup
         worker_kwargs['n_threads'] = self.n_threads
     # Run the worker
     self.logger.info("Running worker against channel layer %s", self.channel_layer)
     try:
         worker = worker_cls(
             channel_layer=self.channel_layer,
             callback=self.callback,
             only_channels=self.options.get("only_channels", None),
             exclude_channels=self.options.get("exclude_channels", None),
             **worker_kwargs
         )
         worker_process_ready.send(sender=worker)
         worker.ready()
         worker.run()
     except KeyboardInterrupt:
         pass
Exemplo n.º 18
0
 def handle(self, *args, **options):
     self.verbosity = options.get("verbosity", 1)
     self.logger = setup_logger('django.channels', self.verbosity)
     self.channel_layer = channel_layers[options.get(
         "layer", DEFAULT_CHANNEL_LAYER)]
     # Check that handler isn't inmemory
     if self.channel_layer.local_only():
         raise CommandError(
             "You cannot span multiple processes with the in-memory layer. "
             + "Change your settings to use a cross-process channel layer.")
     self.options = options
     self.logger.info("Running scheduler against channel layer %s",
                      self.channel_layer)
     try:
         worker = Worker(channel_layer=self.channel_layer, )
         worker.run()
     except KeyboardInterrupt:
         pass
Exemplo n.º 19
0
 def handle(self, *args, **options):
     self.verbosity = options.get("verbosity", 1)
     self.logger = setup_logger('django.channels', self.verbosity)
     self.channel_layer = channel_layers[options.get("layer", DEFAULT_CHANNEL_LAYER)]
     # Check that handler isn't inmemory
     if self.channel_layer.local_only():
         raise CommandError(
             "You cannot span multiple processes with the in-memory layer. " +
             "Change your settings to use a cross-process channel layer."
         )
     self.options = options
     self.logger.info("Running delay against channel layer %s", self.channel_layer)
     try:
         worker = Worker(
             channel_layer=self.channel_layer,
         )
         worker.run()
     except KeyboardInterrupt:
         pass
Exemplo n.º 20
0
 def handle(self, *args, **options):
     # Get the backend to use
     self.verbosity = options.get("verbosity", 1)
     # Get the channel layer they asked for (or see if one isn't configured)
     if "layer" in options:
         self.channel_layer = get_channel_layer(options["layer"])
     else:
         self.channel_layer = get_channel_layer()
     if self.channel_layer is None:
         raise CommandError("You do not have any CHANNEL_LAYERS configured.")
     # Run the worker
     self.logger = setup_logger("django.channels", self.verbosity)
     self.logger.info("Running worker for channels %s", options["channels"])
     worker = self.worker_class(
         application=get_default_application(),
         channels=options["channels"],
         channel_layer=self.channel_layer,
     )
     worker.run()
Exemplo n.º 21
0
 def handle(self, *args, **options):
     # Get the backend to use
     self.verbosity = options.get("verbosity", 1)
     # Get the channel layer they asked for (or see if one isn't configured)
     if "layer" in options:
         self.channel_layer = get_channel_layer(options["layer"])
     else:
         self.channel_layer = get_channel_layer()
     if self.channel_layer is None:
         raise CommandError("You do not have any CHANNEL_LAYERS configured.")
     # Run the worker
     self.logger = setup_logger("django.channels", self.verbosity)
     self.logger.info("Running worker for channels %s", options["channels"])
     worker = self.worker_class(
         application=get_default_application(),
         channels=options["channels"],
         channel_layer=self.channel_layer,
     )
     worker.run()
Exemplo n.º 22
0
 def handle(self, *args, **options):
     # Get the backend to use
     self.verbosity = options.get("verbosity", 1)
     self.logger = setup_logger("django.channels", self.verbosity)
     channel_layer = channel_layers[DEFAULT_CHANNEL_LAYER]
     # Check a handler is registered for http reqs
     if not channel_layer.registry.consumer_for_channel("http.request"):
         # Register the default one
         channel_layer.registry.add_consumer(ViewConsumer(), ["http.request"])
     # Launch a worker
     self.logger.info("Running worker against backend %s", channel_layer.alias)
     # Optionally provide an output callback
     callback = None
     if self.verbosity > 1:
         callback = self.consumer_called
     # Run the worker
     try:
         Worker(channel_layer=channel_layer, callback=callback).run()
     except KeyboardInterrupt:
         pass
Exemplo n.º 23
0
 def handle(self, *args, **options):
     # Get the backend to use
     self.verbosity = options.get("verbosity", 1)
     self.logger = setup_logger('django.channels', self.verbosity)
     channel_layer = channel_layers[DEFAULT_CHANNEL_LAYER]
     # Check a handler is registered for http reqs
     if not channel_layer.registry.consumer_for_channel("http.request"):
         # Register the default one
         channel_layer.registry.add_consumer(ViewConsumer(),
                                             ["http.request"])
     # Launch a worker
     self.logger.info("Running worker against backend %s",
                      channel_layer.alias)
     # Optionally provide an output callback
     callback = None
     if self.verbosity > 1:
         callback = self.consumer_called
     # Run the worker
     try:
         Worker(channel_layer=channel_layer, callback=callback).run()
     except KeyboardInterrupt:
         pass
Exemplo n.º 24
0
def server(bind='127.0.0.1', port=8000, migrate_cmd=False, verbose=1):  # pragma: no cover
    from django.contrib.staticfiles.management.commands import runserver

    if os.environ.get('RUN_MAIN') != 'true':
        _create_db(migrate_cmd)
        User = get_user_model()
        if not User.objects.filter(is_superuser=True).exists():
            usr = create_user('admin', '*****@*****.**', 'admin', is_staff=True,
                              is_superuser=True)
            print('')
            print('A admin user (username: %s, password: admin) '
                  'has been created.' % usr.get_username())
            print('')
    rs = runserver.Command()
    try:
        from django.core.management.base import OutputWrapper
        rs.stdout = OutputWrapper(sys.stdout)
        rs.stderr = OutputWrapper(sys.stderr)
    except ImportError:
        rs.stdout = sys.stdout
        rs.stderr = sys.stderr
    rs.use_ipv6 = False
    rs._raw_ipv6 = False
    rs.addr = bind
    rs.port = port
    try:
        from channels.log import setup_logger
        rs.logger = setup_logger('django.channels', 1)
    except ImportError:
        pass
    autoreload.main(rs.inner_run, (), {
        'addrport': '%s:%s' % (bind, port),
        'insecure_serving': True,
        'use_static_handler': True,
        'use_threading': True,
        'verbosity': verbose,
        'use_reloader': True,
    })
Exemplo n.º 25
0
 def handle(self, *args, **options):
     # Get the backend to use
     self.verbosity = options.get("verbosity", 1)
     self.logger = setup_logger('django.channels', self.verbosity)
     self.channel_layer = channel_layers[options.get("layer", DEFAULT_CHANNEL_LAYER)]
     # Check that handler isn't inmemory
     if self.channel_layer.local_only():
         raise CommandError(
             "You cannot span multiple processes with the in-memory layer. " +
             "Change your settings to use a cross-process channel layer."
         )
     # Check a handler is registered for http reqs
     self.channel_layer.registry.check_default()
     # Launch a worker
     self.logger.info("Running worker against channel layer %s", self.channel_layer)
     # Optionally provide an output callback
     callback = None
     if self.verbosity > 1:
         callback = self.consumer_called
     # Run the worker
     try:
         Worker(channel_layer=self.channel_layer, callback=callback).run()
     except KeyboardInterrupt:
         pass
Exemplo n.º 26
0
 def handle(self, *args, **options):
     # Get the backend to use
     self.verbosity = options.get("verbosity", 1)
     self.logger = setup_logger('django.channels', self.verbosity)
     self.channel_layer = channel_layers[DEFAULT_CHANNEL_LAYER]
     # Check that handler isn't inmemory
     if self.channel_layer.local_only():
         raise CommandError(
             "You cannot span multiple processes with the in-memory layer. "
             + "Change your settings to use a cross-process channel layer.")
     # Check a handler is registered for http reqs
     self.channel_layer.registry.check_default()
     # Launch a worker
     self.logger.info("Running worker against backend %s",
                      self.channel_layer)
     # Optionally provide an output callback
     callback = None
     if self.verbosity > 1:
         callback = self.consumer_called
     # Run the worker
     try:
         Worker(channel_layer=self.channel_layer, callback=callback).run()
     except KeyboardInterrupt:
         pass
Exemplo n.º 27
0
    def handle(self, *args, **options):
        # Get the backend to use
        self.verbosity = options.get("verbosity", 1)
        # Get the channel layer they asked for (or see if one isn't configured)
        if "layer" in options:
            self.channel_layer = get_channel_layer(options["layer"])
        else:
            self.channel_layer = get_channel_layer()
        if self.channel_layer is None:
            raise CommandError(
                "You do not have any CHANNEL_LAYERS configured.")

        # Get beatconfig here.
        from beatserver.parser import Parser
        project_path = settings.SETTINGS_MODULE.replace('.settings', '')
        beat_config = Parser(project_path + '.beatconfig').get_beat_config()

        # Run the worker
        self.logger = setup_logger("django.channels", self.verbosity)
        self.logger.info("Starting beatserver...")
        server = self.server_class(application=get_default_application(),
                                   channel_layer=self.channel_layer,
                                   beat_config=beat_config)
        server.run()
Exemplo n.º 28
0
 def handle(self, *args, **options):
     self.verbosity = options.get('verbosity', 1)
     self.logger = setup_logger('django.channels', self.verbosity)
     manager = self.get_honcho_manager(options)
     manager.loop()
     sys.exit(manager.returncode)
Exemplo n.º 29
0
 def handle(self, *args, **options):
     self.verbosity = options.get('verbosity', 1)
     self.logger = setup_logger('django.channels', self.verbosity)
     manager = self.get_honcho_manager(options)
     manager.loop()
     sys.exit(manager.returncode)
Exemplo n.º 30
0
def server(bind="127.0.0.1",
           port=8000,
           migrate_cmd=False,
           verbose=1):  # pragma: no cover
    try:
        from channels.log import setup_logger
        from channels.management.commands import runserver

        logger = setup_logger("django.channels", 1)
        use_channels = True
    except ImportError:
        from django.contrib.staticfiles.management.commands import runserver

        use_channels = False
        logger = None

    if os.environ.get("RUN_MAIN") != "true":
        _create_db(migrate_cmd)
        User = get_user_model()  # NOQA
        if not User.objects.filter(is_superuser=True).exists():
            usr = create_user("admin",
                              "*****@*****.**",
                              "admin",
                              is_staff=True,
                              is_superuser=True)
            print("")
            print("A admin user (username: %s, password: admin) "
                  "has been created." % usr.get_username())
            print("")
    rs = runserver.Command()
    try:
        from django.core.management.base import OutputWrapper

        rs.stdout = OutputWrapper(sys.stdout)
        rs.stderr = OutputWrapper(sys.stderr)
    except ImportError:
        rs.stdout = sys.stdout
        rs.stderr = sys.stderr
    rs.use_ipv6 = False
    rs._raw_ipv6 = False
    rs.addr = bind
    rs.port = port
    if logger:
        rs.logger = logger
    if use_channels:
        rs.http_timeout = 60
        rs.websocket_handshake_timeout = 5
    try:
        autoreload.run_with_reloader(
            rs.inner_run, **{
                "addrport": "%s:%s" % (bind, port),
                "insecure_serving": True,
                "use_static_handler": True,
                "use_threading": True,
                "verbosity": verbose,
                "use_reloader": True,
            })
    except AttributeError:
        autoreload.main(rs.inner_run,
                        kwargs={
                            "addrport": "%s:%s" % (bind, port),
                            "insecure_serving": True,
                            "use_static_handler": True,
                            "use_threading": True,
                            "verbosity": verbose,
                            "use_reloader": True,
                        })
Exemplo n.º 31
0
 def handle(self, *args, **options):
     self.verbosity = options.get('verbosity', 1)
     self.logger = setup_logger('django.channels', self.verbosity)
     return super(Command, self).handle(*args, **options)
Exemplo n.º 32
0
 def handle(self, *args, **options):
     self.verbosity = options.get("verbosity", 1)
     self.logger = setup_logger('django.channels', self.verbosity)
     super(Command, self).handle(*args, **options)
Exemplo n.º 33
0
 def handle(self, *args, **options):
     self.verbosity = options.get("verbosity", 1)
     self.logger = setup_logger('django.channels', self.verbosity)
     self.http_timeout = options.get("http_timeout", 60)
     self.websocket_handshake_timeout = options.get("websocket_handshake_timeout", 5)
     super(Command, self).handle(*args, **options)
Exemplo n.º 34
0
def ws_disconnect(message):
    """Disconnect a websocket client, cleaning its session."""
    if message.reply_channel.name in CHANNEL_TO_TOKEN:
        token = CHANNEL_TO_TOKEN[message.reply_channel.name]
        setup_logger("server").info("Cleaning session for client %r", token)
        close_session(token)
Exemplo n.º 35
0
from datetime import datetime, date, timedelta
from channels import Channel
from channels.log import setup_logger
from trading.models import Product, Code, Equity, Account, Entry, Exit

logger = setup_logger(__name__)
COMISSION = 7  #수수료


class post:
    @staticmethod
    def save(products):
        """ broker에서 넘어온 시장정보를 db에 업데이트"""
        for group in products.values():

            #상품정보 업데이트
            product, created = Product.objects.update_or_create(
                pk=group['group'],
                defaults={
                    'name':
                    group['name'],
                    'group':
                    group['group'],
                    'market':
                    group['market'],
                    'currency':
                    group['currency'],
                    'open_margin':
                    group['open_margin'],
                    'keep_margin':
                    group['keep_margin'],
Exemplo n.º 36
0
 def handle(self, *args, verbosity=1, **options):
     self.verbosity = verbosity
     self.logger = setup_logger('django.channels', self.verbosity)
     manager = self.get_honcho_manager()
     manager.loop()
     sys_exit(manager.returncode)