Пример #1
0
    def handle(self, addrport="", *args, **options):
        if not addrport:
            self.addr = ""
            self.port = DEFAULT_PORT
        else:
            m = match(naiveip_re, addrport)
            if m is None:
                raise CommandError('"%s" is not a valid port number ' "or address:port pair." % addrport)
            self.addr, _, _, _, self.port = m.groups()

        environ["DJANGO_SOCKETIO_PORT"] = str(self.port)

        if options.get("use_reloader"):
            start_new_thread(reload_watcher, ())

        try:
            bind = (self.addr, int(self.port))
            print "SocketIOServer running on %s:%s\n\n" % bind
            handler = self.get_handler(*args, **options)
            server = SocketIOServer(bind, handler, resource="socket.io", policy_server=True)
            server.serve_forever()
        except KeyboardInterrupt:
            for key, sock in six.iteritems(server.sockets):
                sock.kill(detach=True)
            server.stop()
            if RELOAD:
                print "Reloading...\n\n"
                restart_with_reloader()
Пример #2
0
 def test_manage_py(self):
     argv = ['./manage.py', 'runserver']
     mock_call = self.patch_autoreload(argv)
     autoreload.restart_with_reloader()
     self.assertEqual(mock_call.call_count, 1)
     self.assertEqual(mock_call.call_args[0][0],
                      [self.executable, '-Wall'] + argv)
    def handle(self, *args, **options):
        addrport = options["addrport"]
        m = match(naiveip_re, addrport)
        if m is None:
            raise CommandError(
                "%s is not a valid port number or address:port pair." %
                addrport)

        self.addr, _, _, _, self.port = m.groups()

        # Make the port available allowing the port
        # to be set as the client-side default
        environ["DJANGO_SOCKETIO_PORT"] = str(self.port)

        Thread(target=reload_watcher).start()
        try:
            print("\nSocketIOServer running on {addr}:{port}\n".format(
                addr=self.addr, port=self.port))
            handler = self.get_handler(*args, **options)
            bind = (self.addr, int(self.port))
            server = SocketIOServer(bind,
                                    handler,
                                    resource="socket.io",
                                    policy_server=True)
            server.serve_forever()
        except KeyboardInterrupt:
            if RELOAD:
                server.stop()
                print("Reloading...")
                restart_with_reloader()
            else:
                raise
Пример #4
0
    def handle(self, addrport="", *args, **options):

        if not addrport:
            self.addr = HOST
            self.port = PORT
        else:
            m = match(naiveip_re, addrport)
            if m is None:
                raise CommandError('"%s" is not a valid port number '
                                   'or address:port pair.' % addrport)
            self.addr, _, _, _, self.port = m.groups()

        # Make the port available here for the path:
        #   socketio_tags.socketio ->
        #   socketio_scripts.html ->
        #   io.Socket JS constructor
        # allowing the port to be set as the client-side default there.
        environ["DJANGO_SOCKETIO_PORT"] = str(self.port)

        start_new_thread(reload_watcher, ())
        try:
            bind = (self.addr, int(self.port))
            print
            print "SocketIOServer running on %s:%s" % bind
            print
            handler = self.get_handler(*args, **options)
            server = SocketIOServer(bind, handler, resource="socket.io")
            server.serve_forever()
        except KeyboardInterrupt:
            if RELOAD:
                print
                print "Reloading..."
                restart_with_reloader()
            else:
                raise
Пример #5
0
    def handle(self, addrport="", *args, **options):

        if not addrport:
            self.addr = ''
            self.port = DEFAULT_PORT
        else:
            m = match(naiveip_re, addrport)
            if m is None:
                raise CommandError('"%s" is not a valid port number '
                                   'or address:port pair.' % addrport)
            self.addr, _, _, _, self.port = m.groups()

        # Make the port available here for the path:
        #   socketio_tags.socketio ->
        #   socketio_scripts.html ->
        #   io.Socket JS constructor
        # allowing the port to be set as the client-side default there.
        environ["DJANGO_SOCKETIO_PORT"] = str(self.port)

        start_new_thread(reload_watcher, ())
        try:
            bind = (self.addr, int(self.port))
            print
            print "SocketIOServer running on %s:%s" % bind
            print
            handler = self.get_handler(*args, **options)
            server = SocketIOServer(bind, handler, resource="socket.io", policy_server=True)
            server.serve_forever()
        except KeyboardInterrupt:
            if RELOAD:
                server.stop()
                print "Reloading..."
                restart_with_reloader()
            else:
                raise
Пример #6
0
    def handle(self, addrport="", *args, **options):

        if not addrport:
            self.addr = ''
            self.port = DEFAULT_PORT
        else:
            m = match(naiveip_re, addrport)
            if m is None:
                raise CommandError('"%s" is not a valid port number '
                                   'or address:port pair.' % addrport)
            self.addr, _, _, _, self.port = m.groups()

        # Make the port available here for the path:
        #   socketio_tags.socketio ->
        #   socketio_scripts.html ->
        #   io.Socket JS constructor
        # allowing the port to be set as the client-side default there.
        environ["DJANGO_SOCKETIO_PORT"] = str(self.port)

        start_new_thread(reload_watcher, ())
        try:
            run_socket_server(self.addr, self.port, *args, **options)
        except KeyboardInterrupt:
            if RELOAD:
                server.stop()
                print "Reloading..."
                restart_with_reloader()
            else:
                raise
    def handle(self, addrport="", *args, **options):

        if not addrport:
            self.addr = "127.0.0.1"
            self.port = 9000
        else:
            m = match(naiveip_re, addrport)
            if m is None:
                raise CommandError('"%s" is not a valid port number '
                                   'or address:port pair.' % addrport)
            self.addr, _, _, _, self.port = m.groups()

        start_new_thread(reload_watcher, ())
        try:
            bind = (self.addr, int(self.port))
            print
            print "SocketIOServer running on %s:%s" % bind
            print
            handler = self.get_handler(*args, **options)
            server = SocketIOServer(bind, handler, resource="socket.io")
            server.serve_forever()
        except KeyboardInterrupt:
            if RELOAD:
                print
                print "Reloading..."
                restart_with_reloader()
            else:
                raise
Пример #8
0
 def django_reload(cls):
     try:
         from django.utils.autoreload import restart_with_reloader
         restart_with_reloader()
         from .utils import populate_apps
         populate_apps()
     except Exception as e:
         logger.error(e.message)
Пример #9
0
 def test_python_m_django(self):
     main = '/usr/lib/pythonX.Y/site-packages/django/__main__.py'
     argv = [main, 'runserver']
     mock_call = self.patch_autoreload(argv)
     with mock.patch('django.__main__.__file__', main):
         autoreload.restart_with_reloader()
         self.assertEqual(mock_call.call_count, 1)
         self.assertEqual(mock_call.call_args[0][0], [self.executable, '-Wall', '-m', 'django'] + argv[1:])
Пример #10
0
 def test_python_m_django(self):
     main = '/usr/lib/pythonX.Y/site-packages/django/__main__.py'
     argv = [main, 'runserver']
     mock_call = self.patch_autoreload(argv)
     with mock.patch('django.__main__.__file__', main):
         autoreload.restart_with_reloader()
         self.assertEqual(mock_call.call_count, 1)
         self.assertEqual(mock_call.call_args[0][0], [self.executable, '-Wall', '-m', 'django'] + argv[1:])
Пример #11
0
 def test_manage_py(self):
     script = Path('manage.py')
     script.touch()
     self.addCleanup(script.unlink)
     argv = ['./manage.py', 'runserver']
     mock_call = self.patch_autoreload(argv)
     autoreload.restart_with_reloader()
     self.assertEqual(mock_call.call_count, 1)
     self.assertEqual(mock_call.call_args[0][0],
                      [self.executable, '-Wall'] + argv)
Пример #12
0
 def test_environment(self):
     """"
     With Python 2 on Windows, restart_with_reloader() coerces environment
     variables to str to avoid "TypeError: environment can only contain
     strings" in Python's subprocess.py.
     """
     # With unicode_literals, these values are unicode.
     os.environ['SPAM'] = 'spam'
     with mock.patch.object(sys, 'argv', ['-c', 'pass']):
         autoreload.restart_with_reloader()
Пример #13
0
 def test_environment(self):
     """"
     With Python 2 on Windows, restart_with_reloader() coerces environment
     variables to str to avoid "TypeError: environment can only contain
     strings" in Python's subprocess.py.
     """
     # With unicode_literals, these values are unicode.
     os.environ['SPAM'] = 'spam'
     with mock.patch.object(sys, 'argv', ['-c', 'pass']):
         autoreload.restart_with_reloader()
Пример #14
0
 def test_python_m_django(self):
     main = "/usr/lib/pythonX.Y/site-packages/django/__main__.py"
     argv = [main, "runserver"]
     mock_call = self.patch_autoreload(argv)
     with mock.patch("django.__main__.__file__", main):
         with mock.patch.dict(sys.modules, {"__main__": django.__main__}):
             autoreload.restart_with_reloader()
         self.assertEqual(mock_call.call_count, 1)
         self.assertEqual(
             mock_call.call_args[0][0],
             [self.executable, "-Wall", "-m", "django"] + argv[1:],
         )
Пример #15
0
 def test_manage_py(self):
     with tempfile.TemporaryDirectory() as temp_dir:
         script = Path(temp_dir) / 'manage.py'
         script.touch()
         argv = [str(script), 'runserver']
         mock_call = self.patch_autoreload(argv)
         autoreload.restart_with_reloader()
         self.assertEqual(mock_call.call_count, 1)
         self.assertEqual(
             mock_call.call_args[0][0],
             [self.executable, '-Wall'] + argv,
         )
Пример #16
0
 def test_manage_py(self):
     with tempfile.TemporaryDirectory() as temp_dir:
         script = Path(temp_dir) / "manage.py"
         script.touch()
         argv = [str(script), "runserver"]
         mock_call = self.patch_autoreload(argv)
         with mock.patch("__main__.__spec__", None):
             autoreload.restart_with_reloader()
         self.assertEqual(mock_call.call_count, 1)
         self.assertEqual(
             mock_call.call_args[0][0],
             [self.executable, "-Wall"] + argv,
         )
Пример #17
0
    def run_tests(self):
        auto_reload = False
        if '-a' in sys.argv or '--autoreload' in sys.argv:
            auto_reload = True

        if auto_reload:
            from django.utils.autoreload import restart_with_reloader, reloader_thread
            if os.environ.get("RUN_MAIN") == "true":
                try:
                    TestCommand.run_tests(self)
                except LabelException:
                    sys.exit(1)
                except:
                    pass
                try:
                    reloader_thread()
                except KeyboardInterrupt:
                    pass
            else:
                try:
                    sys.exit(restart_with_reloader())
                except KeyboardInterrupt:
                    pass
        else:
            return TestCommand.run_tests(self)
    def handle(self, addrport='', *args, **options):
        """
        Parses all arguments and starts the server. Will reload on
        SIGINT unless the --noreload flag is passed.
        """

        if options.get('enable_coverage'):
            print "Enabling coverage for socketio server."
            coverage_omit = ['*/management/*',
                             '*/migrations/*']

            cov = coverage.coverage(source=['deckr', 'engine'],
                                    omit=coverage_omit,
                                    data_suffix=True,
                                    branch=True)
            cov.start()

        if not addrport:
            self.addr = ''
            self.port = DEFAULT_PORT

        else:
            address_match = match(naiveip_re, addrport)
            if address_match is None:
                raise CommandError('"%s" is not a valid port number '
                                   'or address:port pair.' % addrport)
            self.addr, _, _, _, self.port = address_match.groups()

        environ['DJANGO_SOCKETIO_PORT'] = str(self.port)
        if options.get('use_reloader'):
            start_new_thread(reload_watcher, ())

        try:
            bind = (self.addr, int(self.port))
            print 'SocketIOServer running on %s:%s\n\n' % bind
            handler = get_handler(**options)
            server = SocketIOServer(
                bind, handler, resource='socket.io', policy_server=True)
            server.serve_forever()
        except KeyboardInterrupt:
            server.stop()
            if options.get('enable_coverage'):
                cov.stop()
                cov.save()
            if RELOAD:
                print 'Reloading...\n\n'
                restart_with_reloader()
    def handle(self, addrport='', *args, **options):
        """
        Parses all arguments and starts the server. Will reload on
        SIGINT unless the --noreload flag is passed.
        """

        if options.get('enable_coverage'):
            print "Enabling coverage for socketio server."
            coverage_omit = ['*/management/*',
                             '*/migrations/*']

            cov = coverage.coverage(source=['deckr'],
                                    omit=coverage_omit,
                                    data_suffix=True)
            cov.start()

        if not addrport:
            self.addr = ''
            self.port = DEFAULT_PORT

        else:
            address_match = match(naiveip_re, addrport)
            if address_match is None:
                raise CommandError('"%s" is not a valid port number '
                                   'or address:port pair.' % addrport)
            self.addr, _, _, _, self.port = address_match.groups()

        environ['DJANGO_SOCKETIO_PORT'] = str(self.port)
        if options.get('use_reloader'):
            start_new_thread(reload_watcher, ())

        try:
            bind = (self.addr, int(self.port))
            print 'SocketIOServer running on %s:%s\n\n' % bind
            handler = get_handler(**options)
            server = SocketIOServer(
                bind, handler, resource='socket.io', policy_server=True)
            server.serve_forever()
        except KeyboardInterrupt:
            server.stop()
            if options.get('enable_coverage'):
                cov.stop()
                cov.save()
            if RELOAD:
                print 'Reloading...\n\n'
                restart_with_reloader()
Пример #20
0
    def handle(self, addrport="", *args, **options):

        if not addrport:
            self.addr = ''
            self.port = DEFAULT_PORT
        else:
            m = match(naiveip_re, addrport)
            if m is None:
                raise CommandError('"%s" is not a valid port number '
                                   'or address:port pair.' % addrport)
            self.addr, _, _, _, self.port = m.groups()

        # Make the port available here for the path:
        #   socketio_tags.socketio ->
        #   socketio_scripts.html ->
        #   io.Socket JS constructor
        # allowing the port to be set as the client-side default there.
        environ["DJANGO_SOCKETIO_PORT"] = str(self.port)

        start_new_thread(reload_watcher, ())
        try:
            bind = (self.addr, int(self.port))
            print
            print "SocketIOServer running on %s:%s" % bind
            print
            handler = self.get_handler(*args, **options)
            manager_conf = getattr(settings, "SOCKET_MANAGER", None)
            kw = {
                  "resource":"socket.io", 
                  "policy_server":True
            }
            if manager_conf:
                kw["socket_manager_config"] = manager_conf
                print "SocketManager settings %s" % manager_conf
            server = SocketIOServer(bind, handler, **kw)
            server.serve_forever()
        except KeyboardInterrupt:
            if RELOAD:
                server.stop()
                print "Reloading..."
                restart_with_reloader()
            else:
                raise
Пример #21
0
    def run(self):

        #         if not addrport:
        #             self.addr = ''
        #             self.port = DEFAULT_PORT
        #         else:
        #             m = match(naiveip_re, addrport)
        #             if m is None:
        #                 raise CommandError('"%s" is not a valid port number '
        #                                    'or address:port pair.' % addrport)
        #             self.addr, _, _, _, self.port = m.groups()

        environ['DJANGO_SOCKETIO_PORT'] = str(self.port)

        #         if options.get('use_psyco'):
        #             try:
        #                 from psycogreen.gevent import patch_psycopg
        #             except ImportError:
        #                 raise CommandError(
        #                     'Could not patch psycopg. '
        #                     'Is psycogreen installed?')
        #             patch_psycopg()

        if self.use_reloader:
            start_new_thread(reload_watcher, ())

        try:
            bind = (self.addr, int(self.port))
            print 'SocketIOServer running on %s:%s\n\n' % bind
            handler = self.get_handler()
            server = self.server = SocketIOServer(bind,
                                                  handler,
                                                  resource='socket.io',
                                                  policy_server=True)
            server.serve_forever()
        except KeyboardInterrupt:
            for key, sock in six.iteritems(server.sockets):
                sock.kill(detach=True)
            server.stop()
            if RELOAD:
                print 'Reloading...\n\n'
                restart_with_reloader()
    def handle(self, addrport='', *args, **options):
        if not addrport:
            self.addr = ''
            self.port = DEFAULT_PORT
        else:
            m = match(naiveip_re, addrport)
            if m is None:
                raise CommandError('"%s" is not a valid port number '
                                   'or address:port pair.' % addrport)
            self.addr, _, _, _, self.port = m.groups()

        environ['DJANGO_SOCKETIO_PORT'] = str(self.port)

        if options.get('use_psyco'):
            try:
                from psycogreen.gevent import patch_psycopg
            except ImportError:
                raise CommandError(
                    'Could not patch psycopg. '
                    'Is psycogreen installed?')
            patch_psycopg()

        if options.get('use_reloader'):
            start_new_thread(reload_watcher, ())

        try:
            bind = (self.addr, int(self.port))
            print 'SocketIOServer running on %s:%s\n\n' % bind
            handler = self.get_handler(*args, **options)
            server = SocketIOServer(
                bind, handler, resource='socket.io', policy_server=True)
            server.serve_forever()
        except KeyboardInterrupt:
            socks = []
            for key, sock in six.iteritems(server.sockets):
                socks.append(sock)
            for sock in socks:
                sock.kill(detach=True)
            server.stop()
            if RELOAD:
                print 'Reloading...\n\n'
                restart_with_reloader()
Пример #23
0
    def handle(self, addrport="", *args, **options):

        if not addrport:
            self.addr = "127.0.0.1"
            self.port = DEFAULT_PORT
        else:
            m = re.match(naiveip_re, addrport)
            if m is None:
                raise CommandError("\"%s\" is not a valid port number "
                                   "or address:port pair." % addrport)
            self.addr, _, _, _, self.port = m.groups()
            if self.addr is None:
                self.addr = "0.0.0.0"

        # Make the port available here for the path:
        #   socketio_tags.socketio ->
        #   socketio_scripts.html ->
        #   io.Socket JS constructor
        # allowing the port to be set as the client-side default there.
        os.environ["DJANGO_SOCKETIO_PORT"] = str(self.port)

        start_new_thread(reload_watcher, ())
        try:
            bind = (self.addr, int(self.port))
            self.stdout.write("Starting development SocketIO server at %s:%s\n" % bind)
            handler = self.get_handler(*args, **options)
            server = SocketIOServer(bind, handler, resource="socket.io", policy_server=True, policy_listener=None)
            server.serve_forever()
        except KeyboardInterrupt:
            if RELOAD:
                server.stop()
                self.stdout.write("Reloading...")
                restart_with_reloader()
            else:
                raise
        except Exception as e:
            raise
Пример #24
0
    def handle(self, *args, **kwargs):
        self.project_dir = os.getcwd()

        signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))
        try:
            if os.environ.get(autoreload.DJANGO_AUTORELOAD_ENV) == "true":
                reloader = autoreload.get_reloader()
                reloader.watch_dir(os.path.join(self.project_dir, "doc"),
                                   "**/*.rst")
                autoreload.logger.info("Watching for file changes with %s",
                                       reloader.__class__.__name__)
                autoreload.start_django(reloader, self.build_and_start_server,
                                        **kwargs)
            else:
                exit_code = autoreload.restart_with_reloader()
                sys.exit(exit_code)
        except KeyboardInterrupt:
            pass
Пример #25
0
 def test_environment_decoding(self):
     """The system encoding is used for decoding."""
     os.environ['SPAM'] = 'spam'
     os.environ['EGGS'] = b'\xc6u vi komprenas?'
     with mock.patch('locale.getdefaultlocale') as default_locale:
         # Latin-3 is the correct mapping.
         default_locale.return_value = ('eo', 'latin3')
         with mock.patch.object(sys, 'argv', ['-c', 'pass']):
             autoreload.restart_with_reloader()
         # CP1252 interprets latin3's C circumflex as AE ligature.
         # It's incorrect but doesn't raise an error.
         default_locale.return_value = ('en_US', 'cp1252')
         with mock.patch.object(sys, 'argv', ['-c', 'pass']):
             autoreload.restart_with_reloader()
         # Interpreting the string as UTF-8 is fatal.
         with self.assertRaises(UnicodeDecodeError):
             default_locale.return_value = ('en_US', 'utf-8')
             with mock.patch.object(sys, 'argv', ['-c', 'pass']):
                 autoreload.restart_with_reloader()
Пример #26
0
 def test_environment_decoding(self):
     """The system encoding is used for decoding."""
     os.environ['SPAM'] = 'spam'
     os.environ['EGGS'] = b'\xc6u vi komprenas?'
     with mock.patch('locale.getdefaultlocale') as default_locale:
         # Latin-3 is the correct mapping.
         default_locale.return_value = ('eo', 'latin3')
         with mock.patch.object(sys, 'argv', ['-c', 'pass']):
             autoreload.restart_with_reloader()
         # CP1252 interprets latin3's C circumflex as AE ligature.
         # It's incorrect but doesn't raise an error.
         default_locale.return_value = ('en_US', 'cp1252')
         with mock.patch.object(sys, 'argv', ['-c', 'pass']):
             autoreload.restart_with_reloader()
         # Interpreting the string as UTF-8 is fatal.
         with self.assertRaises(UnicodeDecodeError):
             default_locale.return_value = ('en_US', 'utf-8')
             with mock.patch.object(sys, 'argv', ['-c', 'pass']):
                 autoreload.restart_with_reloader()
Пример #27
0
 def test_manage_py(self):
     argv = ['./manage.py', 'runserver']
     mock_call = self.patch_autoreload(argv)
     autoreload.restart_with_reloader()
     self.assertEqual(mock_call.call_count, 1)
     self.assertEqual(mock_call.call_args[0][0], [self.executable, '-Wall'] + argv)
Пример #28
0
    def handle(self, addrport='', *args, **options):
        if args:
            raise CommandError('Usage is server %s' % self.args)
        if not addrport:
            self.addr = ''
            self.port = DEFAULT_PORT
        else:
            m = re.match(naiveip_re, addrport)
            if m is None:
                raise CommandError('"%s" is not a valid port number '
                                   'or address:port pair.' % addrport)
            self.addr, _ipv4, _ipv6, _fqdn, self.port = m.groups()
            if not self.port.isdigit():
                raise CommandError("%r is not a valid port number." %
                                   self.port)
            if self.addr and _ipv6:
                raise CommandError("ipv6 is not supported")

        if not self.addr:
            self.addr = '127.0.0.1'

        if options.get('apiprefix') and not options.get('prefix'):
            raise CommandError("--apiprefix can only be used in conjuction "
                               "with --prefix. ")

        logger = logging.getLogger('feat')
        if options.get('featlog'):
            log.FluLogKeeper.init(options['featlog'])
            log.set_default(log.FluLogKeeper())
            log.info('featdjango',
                     'Use feat logging: %s' % (options['featlog'], ))
        else:
            log.set_default(log.PythonLogKeeper(logger))
            from feat.extern.log import log as flulog
            flulog.setPackageScrubList('featcredex', 'featdjango', 'feat')
            log.info('featdjango', 'Use python logging')

        log.info('featdjango', "Listening on %s:%s", self.addr, self.port)

        if os.environ.get("RUN_MAIN") == 'true':
            # this is how django autoreloader lets the child process know
            # that its a child process
            if options.get('elflog_path'):
                stats = webserver.ELFLog(options.get('elflog_path'),
                                         options.get('elflog_fields'))
            else:
                stats = None

            site = server.Server(self.addr,
                                 int(self.port),
                                 prefix=options.get('prefix'),
                                 apiprefix=options.get('apiprefix'),
                                 web_statistics=stats,
                                 thread_stats_file=options.get('stats_file'))
            reactor.callWhenRunning(site.initiate)
            reactor.addSystemEventTrigger('before', 'shutdown', site.cleanup)

            if options.get('use_reloader'):
                task = reloader.Reloader(reactor, site)
                reactor.callWhenRunning(task.run)

            reactor.run()

            if options.get('use_reloader'):
                if task.should_reload:
                    sys.exit(3)
        else:
            # in the original process we just spawn the child worker as
            # many times as it tells us to
            try:
                while autoreload.restart_with_reloader() == 3:
                    pass
            except KeyboardInterrupt:
                pass
Пример #29
0
 def django_reload(cls):
     try:
         from django.utils.autoreload import restart_with_reloader
         restart_with_reloader()
     except Exception as e:
         logger.error(str(e))
Пример #30
0
    def handle(self, addrport='', *args, **options):
        if args:
            raise CommandError('Usage is server %s' % self.args)
        if not addrport:
            self.addr = ''
            self.port = DEFAULT_PORT
        else:
            m = re.match(naiveip_re, addrport)
            if m is None:
                raise CommandError('"%s" is not a valid port number '
                                   'or address:port pair.' % addrport)
            self.addr, _ipv4, _ipv6, _fqdn, self.port = m.groups()
            if not self.port.isdigit():
                raise CommandError(
                    "%r is not a valid port number." % self.port)
            if self.addr and _ipv6:
                raise CommandError("ipv6 is not supported")

        if not self.addr:
            self.addr = '127.0.0.1'

        if options.get('apiprefix') and not options.get('prefix'):
            raise CommandError("--apiprefix can only be used in conjuction "
                               "with --prefix. ")

        logger = logging.getLogger('feat')
        if options.get('featlog'):
            log.FluLogKeeper.init(options['featlog'])
            log.set_default(log.FluLogKeeper())
            log.info('featdjango', 'Use feat logging: %s' % (
                options['featlog'], ))
        else:
            log.set_default(log.PythonLogKeeper(logger))
            from feat.extern.log import log as flulog
            flulog.setPackageScrubList('featcredex', 'featdjango', 'feat')
            log.info('featdjango', 'Use python logging')

        log.info('featdjango', "Listening on %s:%s", self.addr, self.port)

        if os.environ.get("RUN_MAIN") == 'true':
            # this is how django autoreloader lets the child process know
            # that its a child process
            if options.get('elflog_path'):
                stats = webserver.ELFLog(options.get('elflog_path'),
                                         options.get('elflog_fields'))
            else:
                stats = None

            site = server.Server(self.addr, int(self.port),
                                 prefix=options.get('prefix'),
                                 apiprefix=options.get('apiprefix'),
                                 web_statistics=stats,
                                 thread_stats_file=options.get('stats_file'))
            reactor.callWhenRunning(site.initiate)
            reactor.addSystemEventTrigger('before', 'shutdown', site.cleanup)

            if options.get('use_reloader'):
                task = reloader.Reloader(reactor, site)
                reactor.callWhenRunning(task.run)

            reactor.run()

            if options.get('use_reloader'):
                if task.should_reload:
                    sys.exit(3)
        else:
            # in the original process we just spawn the child worker as
            # many times as it tells us to
            try:
                while autoreload.restart_with_reloader() == 3:
                    pass
            except KeyboardInterrupt:
                pass
Пример #31
0
 def handle(self, *args, **kwargs):
     """Run the websocket server."""
     
     # Set the settings module for the websocket server.
     if 'DJANGO_SETTINGS_MODULE' not in os.environ:
         os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
     
     # Import the WSGI handler.
     application = self.get_handler(*args, **kwargs)
     
     # Print nice things to the console; make it look mostly like
     # the traditional Django dev server.
     print "Django version {version}, using settings '{settings}'.".format(
         settings=os.environ['DJANGO_SETTINGS_MODULE'],
         version=django.get_version(),
     )
     print ' '.join((
         'SocketIO server is listening on port %d' % kwargs['port'],
         'and on port 843 (Flash policy server).',
     ))
     print 'Quit the server with CONTROL-C.'
     
     # Create the SocketIO server.
     # Pay special attention here to the `resource` keyword argument.
     #   The SocketIO server will only do SocketIO connections on URIs
     #   starting with this resource. So, using "socket.io" as your
     #   resource means that the SocketIO server expects its special
     #   connections to come in at `http://domain.com/socket.io/foo/`.
     # The default on both the Python side and the JavaScript side
     #   is "socket.io", and this is probably the best choice. It's possible
     #   to use something else, but it has to match everywhere and most
     #   likely won't be very DRY unless you jump a lot of hoops.
     socket_io_server = SocketIOServer(
         (kwargs['host'], kwargs['port']),
         application,
         resource='socket.io',
         policy_server=True,
     )
     
     # Set up the socket io server to actually serve; use the
     # auto-reloader if desired.
     use_reloader = kwargs['use_reloader']
     if use_reloader:
         spawn(reload_watcher)
     
     # Run the socket.io server within a try/except block
     # (so that if it is shut down, it can be restarted).
     try:
         socket_io_server.serve_forever()
     except KeyboardInterrupt:
         global _server_should_reload
         if _server_should_reload:
             # Set my "should reload" variable back to False.
             _server_should_reload = False
             
             # Kill the server.
             socket_io_server.kill()
             socket_io_server = None
             
             # Now, reload a new server.
             print '\nReloading server...'
             restart_with_reloader()
         else:
             print '\r\n\n'
             sys.exit(0)