Beispiel #1
0
 def __init__(self):
     BaseCommand.__init__(self)
     self.style = no_style()
     # Keep a count of the installed objects and ontologies
     self.count = [0, 0]
     self.models = set()
     self.verbosity, self.show_traceback, self.fail_gracefully = 1, False, False
Beispiel #2
0
    def __init__(self, *args, **kwargs):

        self.verbosity = 0
        self.stats = {}
        self._ignore = []

        BaseCommand.__init__(self, *args, **kwargs)
Beispiel #3
0
 def __init__(self, *args, **kwargs):
     """
         Creation of the ejabberd atuh bridge service.
         :Parameters:
             - `args`: all non-keyword arguments
             - `kwargs`: all keyword arguments
     """
     BaseCommand.__init__(self, *args, **kwargs)
     try:
         log_level = int(logging.DEBUG)
     except:
         log_level = logging.INFO
     if os.access("/var/log/ejabberd/kauth.log", os.W_OK):
         logging.basicConfig(level=log_level,
                             format='%(asctime)s %(levelname)s %(message)s',
                             filename="/var/log/ejabberd/kauth.log",
                             filemode='a')
     else:
         logging.basicConfig(level=log_level,
                             format='%(asctime)s %(levelname)s %(message)s',
                             stream=sys.stderr)
         logging.warn(
             ('Could not write to ' + '/var/log/ejabberd/kauth.log' +
              '. Falling back to stderr ...'))
     logging.info(
         ('ejabberd kauth process started' + ' (more than one is common)'))
    def __init__(self, *args, **kwargs):
        class NiceContext(Context):
            """
            Same as the real context class, but override some methods in order to gain
            nice colored output.
            """
            def __init__(s, *args, **kwargs):
                kwargs['insert_debug_symbols'] = self.insert_debug_symbols
                Context.__init__(s, *args, **kwargs)

            def compile_media_callback(s, compress_tag, media_files):
                """
                When the compiler notifies us that compiling of this file begins.
                """
                if compress_tag:
                    print self.colored('Compiling media files from', 'yellow'),
                    print self.colored(' "%s" ' % compress_tag.path, 'green'),
                    print self.colored(' (line %s, column %s)" ' % (compress_tag.line, compress_tag.column), 'yellow')
                else:
                    print self.colored('Compiling media files', 'yellow')

                for m in media_files:
                    print self.colored('   * %s' % m, 'green')

            def compile_media_progress_callback(s, compress_tag, media_file, current, total, file_size):
                """
                Print progress of compiling media files.
                """
                print self.colored('       (%s / %s):' % (current, total), 'yellow'),
                print self.colored(' %s (%s bytes)' % (media_file, file_size), 'green')
        self.NiceContext = NiceContext

        BaseCommand.__init__(self, *args, **kwargs)
Beispiel #5
0
    def __init__(self, *args, **kwargs):

        self.verbosity = 0
        self.stats = {}
        self._ignore = []

        BaseCommand.__init__(self, *args, **kwargs)
Beispiel #6
0
    def __init__(self):
        BaseCommand.__init__(self)

        self.option_list += (make_option(
            '--queues',
            '-q',
            help='Queues to include (default: all). Use queue slugs'), )
Beispiel #7
0
    def add_arguments(self, parser):
        BaseCommand.add_arguments(self, parser)

        parser.add_argument('addrport', nargs='?',
            help='Optional port number, or ipaddr:port')

        # The below flags are for legacy compat.
        # 2017-06-08 added addrport positional argument,
        # because:
        # - more consistent with runserver.
        # - don't have to remember the name of the flags (is it --bind or --addr etc)
        # - quicker to type
        # - we don't need positional args for anything else

        parser.add_argument(
            '--addr', action='store', type=str, dest='addr', default=None,
            help='The host/address to bind to (default: {})'.format(DEFAULT_ADDR))

        ahelp = (
            'Port number to listen on. Defaults to the environment variable '
            '$PORT (if defined), or {}.'.format(DEFAULT_PORT)
        )
        parser.add_argument(
            '--port', action='store', type=int, dest='port', default=None,
            help=ahelp)
    def __init__(self, *args, **kwargs):
        """
        Creation of the ejabberd atuh bridge service.

        :Parameters:
           - `args`: all non-keyword arguments
           - `kwargs`: all keyword arguments
        """
        BaseCommand.__init__(self, *args, **kwargs)
        try:
            log_level = int(settings.TUNNEL_EJABBERD_AUTH_GATEWAY_LOG_LEVEL)
        except:
            log_level = logging.INFO
        # If we can write to the log do so, else fail back to the console
        if os.access(settings.TUNNEL_EJABBERD_AUTH_GATEWAY_LOG, os.W_OK):
            logging.basicConfig(
                level=log_level,
                format='%(asctime)s %(levelname)s %(message)s',
                filename=settings.TUNNEL_EJABBERD_AUTH_GATEWAY_LOG,
                filemode='a')
        else:
            logging.basicConfig(
                level=log_level,
                format='%(asctime)s %(levelname)s %(message)s',
                stream=sys.stderr)
            logging.warn(('Could not write to ' +
                settings.TUNNEL_EJABBERD_AUTH_GATEWAY_LOG +
                '. Falling back to stderr ...'))
        logging.info(('ejabberd_auth_bridge process started' +
            ' (more than one is common)'))
Beispiel #9
0
 def __init__(self):
     BaseCommand.__init__(self)
     self.option_list += (make_option('--quiet',
                                      '-q',
                                      default=False,
                                      action='store_true',
                                      help='Hide all command output'), )
Beispiel #10
0
    def add_arguments(self, parser):
        BaseCommand.add_arguments(self, parser)

        parser.add_argument('addrport', nargs='?',
            help='Optional port number, or ipaddr:port')

        # The below flags are for legacy compat.
        # 2017-06-08 added addrport positional argument,
        # because:
        # - more consistent with runserver.
        # - don't have to remember the name of the flags (is it --bind or --addr etc)
        # - quicker to type
        # - we don't need positional args for anything else

        parser.add_argument(
            '--addr', action='store', type=str, dest='addr', default=None,
            help='The host/address to bind to (default: {})'.format(DEFAULT_ADDR))

        ahelp = (
            'Port number to listen on. Defaults to the environment variable '
            '$PORT (if defined), or {}.'.format(DEFAULT_PORT)
        )
        parser.add_argument(
            '--port', action='store', type=int, dest='port', default=None,
            help=ahelp)
        ahelp = (
            'Run an SSL server directly in Daphne with a self-signed cert/key'
        )
        parser.add_argument(
            '--dev-https', action='store_true', dest='dev_https', default=False,
            help=ahelp)
Beispiel #11
0
    def add_arguments(self, parser):
        BaseCommand.add_arguments(self, parser)

        ahelp = ('TODO')
        parser.add_argument('--reload',
                            action='store_true',
                            dest='use_reloader',
                            default=False,
                            help=ahelp)

        ahelp = (
            'The port that the http server should run on. It defaults to '
            '5000. This value can be set by the environment variable $PORT.')
        parser.add_argument('--port',
                            action='store',
                            type=int,
                            dest='port',
                            default=None,
                            help=ahelp)
        parser.add_argument('--addr',
                            action='store',
                            type=str,
                            dest='addr',
                            default='0.0.0.0',
                            help=ahelp)
Beispiel #12
0
    def add_arguments(self, parser):
        BaseCommand.add_arguments(self, parser)

        ahelp = ('TODO')
        parser.add_argument('--reload',
                            action='store_true',
                            dest='use_reloader',
                            default=False,
                            help=ahelp)
        ahelp = (
            'Port number to listen on. Defaults to the environment variable '
            '$PORT (if defined), or 8000.')
        parser.add_argument('--port',
                            action='store',
                            type=int,
                            dest='port',
                            default=None,
                            help=ahelp)
        parser.add_argument(
            '--addr',
            action='store',
            type=str,
            dest='addr',
            default='0.0.0.0',
            help='The host/address to bind to (default: 0.0.0.0)')
        parser.add_argument(
            '--botworker',
            action='store_true',
            dest='botworker',
            default=False,
            help='--botworker flag is deprecated and has no effect')
Beispiel #13
0
 def __init__(self, *args, **kwargs):
     """
         Creation of the ejabberd atuh bridge service.
         :Parameters:
             - `args`: all non-keyword arguments
             - `kwargs`: all keyword arguments
     """
     BaseCommand.__init__(self, *args, **kwargs)
     try:
         log_level = int(logging.DEBUG)
     except:
         log_level = logging.INFO
     if os.access("/var/log/ejabberd/kauth.log", os.W_OK):
         logging.basicConfig(
                             level=log_level,
                             format='%(asctime)s %(levelname)s %(message)s',
                             filename="/var/log/ejabberd/kauth.log",
                             filemode='a')
     else:
         logging.basicConfig(
                             level=log_level,
                             format='%(asctime)s %(levelname)s %(message)s',
                             stream=sys.stderr)
         logging.warn(('Could not write to ' +
                       '/var/log/ejabberd/kauth.log' +
                       '. Falling back to stderr ...'))
     logging.info(('ejabberd kauth process started' +' (more than one is common)'))
    def __init__(self):
        BaseCommand.__init__(self)

        self.option_list += (
            make_option("--queues", "-q", help="Queues to include (default: all). Use queue slugs"),
            make_option("--verbose", "-v", action="store_true", default=False, help="Display a list of dates excluded"),
        )
Beispiel #15
0
 def add_arguments(self, parser: argparse.ArgumentParser) -> None:
     BaseCommand.add_arguments(self, parser)
     parser.add_argument('--discovery',
                         action='store',
                         type=str,
                         required=True,
                         help=pgettext_lazy(
                             'Scanner Custom',
                             'Discovery to execute'))
     parser.add_argument('--disabled',
                         action='store_true',
                         default=False,
                         help=pgettext_lazy(
                             'Scanner Custom',
                             'Launch also disabled discoveries'))
     parser.add_argument('--failing',
                         action='store_true',
                         default=False,
                         help=pgettext_lazy(
                             'Scanner Custom',
                             'Save results also for failing hosts'))
     parser.add_argument('--destinations',
                         action='store',
                         type=str,
                         required=False,
                         help=pgettext_lazy(
                             'Scanner Custom',
                             'Execute the discovery only to the selected '
                             'destinations'))
    def __init__(self):
        BaseCommand.__init__(self)

        self.option_list += (
            make_option("--days",
                        "-d",
                        help="Days of week (monday, tuesday, etc)"),
            make_option(
                "--occurrences",
                "-o",
                type="int",
                default=1,
                help="Occurrences: How many weeks ahead to exclude this day",
            ),
            make_option(
                "--queues",
                "-q",
                help="Queues to include (default: all). Use queue slugs",
            ),
            make_option(
                "--escalate-verbosely",
                "-x",
                action="store_true",
                default=False,
                help="Display a list of dates excluded",
            ),
        )
Beispiel #17
0
    def __init__(self, *args, **kwargs):
        """
        Creation of the ejabberd atuh bridge service.

        :Parameters:
           - `args`: all non-keyword arguments
           - `kwargs`: all keyword arguments
        """
        BaseCommand.__init__(self, *args, **kwargs)
        #        try:
        #            log_level = int(settings.TUNNEL_EJABBERD_AUTH_GATEWAY_LOG_LEVEL)
        #        except:
        log_level = logging.INFO
        # If we can write to the log do so, else fail back to the console
        #if os.access(settings.TUNNEL_EJABBERD_AUTH_GATEWAY_LOG, os.W_OK):
        #    logging.basicConfig(
        #        level=log_level,
        #        format='%(asctime)s %(levelname)s %(message)s',
        #        filename=settings.TUNNEL_EJABBERD_AUTH_GATEWAY_LOG,
        #        filemode='a')
        #else:
        logging.basicConfig(level=log_level,
                            format='%(asctime)s %(levelname)s %(message)s',
                            stream=sys.stderr)
        #logging.warn(('Could not write to ' +
        #        settings.TUNNEL_EJABBERD_AUTH_GATEWAY_LOG +
        #        '. Falling back to stderr ...'))
        logging.info(('ejabberd_auth_bridge process started' +
                      ' (more than one is common)'))
Beispiel #18
0
 def __init__(self):
     BaseCommand.__init__(self)
     self.skipped_users = []
     self.skipped_products = []
     self.skipped_logos = []
     self.skipped_pics = []
     signal.signal(signal.SIGINT, self.handle_interrupt)
Beispiel #19
0
 def __init__(self, *args, **kwargs):
     BaseCommand.__init__(self, *args, **kwargs)
     self.target = None
     self.files_in_export_dir = []
     self.exported_files = []
     self.compare_checksums = False
     self.use_filename_format = False
     self.delete = False
    def __init__(self, *args, **kwargs):

        self.verbosity = 0

        self.file_consumer = None
        self.mail_fetcher = None

        BaseCommand.__init__(self, *args, **kwargs)
    def __init__(self):
        BaseCommand.__init__(self)

        self.option_list += (
            make_option(
                '--queues', '-q',
                help='Queues to include (default: all). Use queue slugs'),
            )
    def __init__(self, *args, **kwargs):

        self.verbosity = 0

        self.file_consumer = None
        self.mail_fetcher = None

        BaseCommand.__init__(self, *args, **kwargs)
Beispiel #23
0
 def __init__(self):
     BaseCommand.__init__(self)
     self.found = 0
     self.no_match = 0
     from_coord = SpatialReference(900913)
     to_coord = SpatialReference(4326)
     self.trans = CoordTransform(from_coord, to_coord)
     self.rtrans = CoordTransform(to_coord, from_coord)
Beispiel #24
0
    def __init__(self, *args, **kwargs):

        self.logger = logging.getLogger(__name__)

        BaseCommand.__init__(self, *args, **kwargs)

        self.username = settings.MAIL_POLLING["username"]
        self.password = settings.MAIL_POLLING["password"]
        self.host = settings.MAIL_POLLING["host"]
Beispiel #25
0
 def __init__(self):
     BaseCommand.__init__(self)
     self.option_list += (
         make_option(
             '--quiet', '-q',
             default=False,
             action='store_true',
             help='Hide all command output'),
         )
Beispiel #26
0
 def __init__(self, *largs, **kwargs):
     BaseCommand.__init__(self, *largs, **kwargs)
     from django.conf import settings
     self.cascade = False
     if settings.DATABASE_ENGINE:
         self.cascade = settings.DATABASE_ENGINE.find('postgresql') >= 0
     elif settings.DATABASES:
         db_settings = settings.DATABASES.get('default')
         self.cascade = db_settings.get('ENGINE').find('postgresql') >= 0
Beispiel #27
0
    def __init__(self):
        BaseCommand.__init__(self)

        self.option_list += (make_option(
            '--quiet',
            '-q',
            default=False,
            action='store_true',
            help='Hide details about each message as they are processed.'), )
 def __init__(self, *args, **kwargs):
     BaseCommand.__init__(self, *args, **kwargs)
     self.local_enabled = False
     # Change this to True to log requests for debug *logs may include passwords*
     self.LOGGING_ENABLED = False
     if get_config("JABBER_LOCAL_ENABLED",None).value == "1":
         self.local_enabled = True
         self.local_user = get_config("JABBER_FROM_JID", False).value.split('@')[0]
         self.local_pass = get_config("JABBER_FROM_PASSWORD", False).value
         self.space_char = get_config("JABBER_LOCAL_SPACE_CHAR", False).value
    def __init__(self, *args, **kwargs):

        self.verbosity = 0
        self.logger = logging.getLogger(__name__)

        self.file_consumer = None
        self.mail_fetcher = None
        self.first_iteration = True

        BaseCommand.__init__(self, *args, **kwargs)
Beispiel #30
0
    def __init__(self):
        BaseCommand.__init__(self)

        self.option_list += (
            make_option(
                '--quiet', '-q',
                default=False,
                action='store_true',
                help='Hide details about each queue/message as they are processed'),
            )
 def __init__(self, *args, **kwargs):
     BaseCommand.__init__(self, *args, **kwargs)
     self.local_enabled = False
     # Change this to True to log requests for debug *logs may include passwords*
     self.LOGGING_ENABLED = False
     if get_config("JABBER_LOCAL_ENABLED",None).value == "1":
         self.local_enabled = True
         self.local_user = get_config("JABBER_FROM_JID", False).value.split('@')[0]
         self.local_pass = get_config("JABBER_FROM_PASSWORD", False).value
         self.space_char = get_config("JABBER_LOCAL_SPACE_CHAR", False).value
 def __init__(self):
     """
     Host base command for all management host commands
     """
     BaseCommand.__init__(self)
     # Automatically save a DiscoveryResult record for each successful
     # discovery result
     self.save_results = True
     # Verbosity level for printing results
     self.verbosity = 0
Beispiel #33
0
    def __init__(self):
        BaseCommand.__init__(self)
        self.address = '127.0.0.1'
        #TODO: add some function for server/crawler address creation;
        # now it can be bugged with large numbers of servers/crawlers
        self.server_port = max([int(server.address.split(':')[2]) for server in TaskServer.objects.all()] + [INIT_SERVER_PORT]) + 1
        self.crawler_port = max([int(crawler.address.split(':')[2]) for crawler in Crawler.objects.all()] + [INIT_CRAWLER_PORT]) + 1

        self.last_scaling = time.time()
        self.old_crawlers = [crawler.address for crawler in Crawler.objects.all()]
        self.changed = False
Beispiel #34
0
    def __init__(self, *args, **kwargs):
        BaseCommand.__init__(self, *args, **kwargs)

        # TODO: use Django settings to configure the logger
        # https://docs.djangoproject.com/en/3.1/topics/logging/
        logger = logging.getLogger()
        logger.setLevel(logging.INFO)
        handler = logging.StreamHandler()
        formatter = logging.Formatter("{levelname:8} {message}", style="{")
        handler.setFormatter(formatter)
        logger.addHandler(handler)
Beispiel #35
0
 def __init__(self):
     """
     Discovery base command for all management discovery commands
     Use scanner_tool string to choose the desider scanner to use
     """
     BaseCommand.__init__(self)
     # Automatically save a DiscoveryResult record for each successful
     # discovery result
     self.save_results = True
     # Verbosity level for printing results
     self.verbosity = 0
Beispiel #36
0
 def __init__(self):
     BaseCommand.__init__(self)
     self.logger = getLogger("Review Progress")
     self.logger.setLevel(logging.DEBUG)
     stream_handler = StreamHandler()
     file_handler = FileHandler('crawl_progress.log', 'a')
     handler_format = Formatter('%(asctime)s - %(message)s')
     stream_handler.setFormatter(handler_format)
     file_handler.setFormatter(handler_format)
     self.logger.addHandler(stream_handler)
     self.logger.addHandler(file_handler)
     stream_handler.setLevel(logging.DEBUG)
Beispiel #37
0
    def __init__(self):
        BaseCommand.__init__(self)

        self.option_list = (
            make_option(
                '--queues',
                help='Queues to include (default: all). Use queue slugs'),
            make_option('--verboseescalation',
                        action='store_true',
                        default=False,
                        help='Display a list of dates excluded'),
        )
Beispiel #38
0
 def add_arguments(self, parser: argparse.ArgumentParser) -> None:
     BaseCommand.add_arguments(self, parser)
     parser.add_argument('--host',
                         action='store',
                         type=str,
                         required=True,
                         help=pgettext_lazy('Ping', 'Host to ping'))
     parser.add_argument('--count',
                         action='store',
                         type=int,
                         default=0,
                         help=pgettext_lazy('Ping', 'Max ping count'))
Beispiel #39
0
    def __init__(self):
        BaseCommand.__init__(self)

        self.option_list += (
            make_option(
                "--quiet",
                "-q",
                default=False,
                action="store_true",
                help="Hide details about each message as they are processed.",
            ),
        )
    def __init__(self):
        BaseCommand.__init__(self)

        self.option_list += (
            make_option(
                '--queues',
                help='Queues to include (default: all). Use queue slugs'),
            make_option(
                '--verboseescalation',
                action='store_true',
                default=False,
                help='Display a list of dates excluded'),
            )
Beispiel #41
0
    def __init__(self):
        BaseCommand.__init__(self)
        self.address = '127.0.0.1'  # TODO - ENVIRONMENT DEPENDANT: change management address
        signal.signal(signal.SIGINT, sigint_signal_handler)
        #TODO - FUTURE WORKS: add some function for server/crawler address creation;
        # now it can be bugged with large numbers of servers/crawlers
        self.server_port = max([int(server.address.split(':')[2]) for server in TaskServer.objects.all()]
                               + [INIT_SERVER_PORT]) + 1
        self.crawler_port = max([int(crawler.address.split(':')[2]) for crawler in Crawler.objects.all()]
                                + [INIT_CRAWLER_PORT]) + 1

        self.last_scaling = time.time()
        self.old_crawlers = [crawler.address for crawler in Crawler.objects.all()]
        self.changed = False
    def __init__(self):
        BaseCommand.__init__(self)

        self.option_list += (
            make_option(
                "--queues",
                help="Queues to include (default: all). Use queue slugs"),
            make_option(
                "--verboseescalation",
                action="store_true",
                default=False,
                help="Display a list of dates excluded",
            ),
        )
Beispiel #43
0
def make_wsgi_application():
    # validate models
    s = StringIO()
    import django
    from django.core.management.base import BaseCommand
    django.setup()
    cmd = BaseCommand()
    import sys
    cmd.stdout, cmd.stderr = sys.stdout, sys.stderr
    cmd.check()
    translation.activate(settings.LANGUAGE_CODE)
    if django14:
        return get_internal_wsgi_application()
    return WSGIHandler()
Beispiel #44
0
 def add_arguments(self, parser: argparse.ArgumentParser) -> None:
     BaseCommand.add_arguments(self, parser)
     parser.add_argument('--filename',
                         action='store',
                         type=str,
                         required=True,
                         help=pgettext('Load OUI IEEE MA-L', 'filename'))
     parser.add_argument('--count',
                         action='store',
                         type=int,
                         required=False,
                         default=1000,
                         help=pgettext('Load OUI IEEE MA-L',
                                       'items count to insert per batch'))
Beispiel #45
0
    def __init__(self):

        BaseCommand.__init__(self)
        self.tracking = []
        self.streams = {}
        self.first_pass_completed = False
        self.verbosity = 1

        self._wait_for_db()

        self.socialapp = SocialApp.objects.get(pk=1)

        os.makedirs(os.path.join(Archive.ARCHIVES_DIR, "raw"), exist_ok=True)
        os.makedirs(os.path.join(Archive.ARCHIVES_DIR, "map"), exist_ok=True)
Beispiel #46
0
 def __init__(self, *args, **kwargs):
     BaseCommand.__init__(self, *args, **kwargs)
     self.actions = {
         "help": "show help information",
         ReviewMethod.name: [
             ReviewMethod,
         ],
         PracticeMethod.name: [
             PracticeMethod,
         ],
         HardMethod.name: [
             HardMethod,
         ],
         "dictation": [HardMethod, ReviewMethod],
     }
Beispiel #47
0
 def __init__(self):
     BaseCommand.__init__(self)
     self.option_list += (make_option('--quiet',
                                      '-q',
                                      default=False,
                                      action='store_true',
                                      help='Hide all command output.'), )
     self.option_list += (make_option(
         '--prod-indexes',
         '-p',
         default=False,
         action='store_true',
         help=
         'Delete all production databases indexes in CouchDB. e.g. "dmscouch" and "mdtcouch" databases.'
     ), )
Beispiel #48
0
 def __init__(self):
     BaseCommand.__init__(self)
     self.option_list += (
         make_option(
             '--quiet', '-q',
             default=False,
             action='store_true',
             help='Hide all command output.'),
     )
     self.option_list += (
         make_option(
             '--prod-indexes', '-p',
             default=False,
             action='store_true',
             help='Delete all production databases indexes in CouchDB. e.g. "dmscouch" and "mdtcouch" databases.'),
     )
Beispiel #49
0
 def test_import_csv_user_basic(self, requests_post, utils_get_landowner):
     """Check if parsing a wellformed CSV works fine"""
     cmd = BaseCommand()
     grp = Group(name='theuser')
     grp.save()
     ubi = UserImporter(cmd, './legacy/tests/basic-users-mapping.csv')
     self.assertEqual(User.objects.count(), 4)
Beispiel #50
0
 def validate_models(self):
     s = io.StringIO()
     try:
         from django.core.management.validation import get_validation_errors
     except ImportError:
         import django
         from django.core.management.base import BaseCommand
         django.setup()
         cmd = BaseCommand()
         cmd.stdout, cmd.stderr = sys.stdout, sys.stderr
         cmd.check()
     else:
         num_errors = get_validation_errors(s, None)
         if num_errors:
             raise RuntimeError(
                 'One or more Django models did not validate:\n{0}'.format(
                     s.getvalue()))
Beispiel #51
0
 def test_import_csv_categories_clean(self, requests_post,
                                      utils_get_landowner):
     """Check if clean removes existing objects"""
     cat = Category(name='Testcategory')
     cat.save()
     cmd = BaseCommand()
     cati = CategoryImporter(cmd, './legacy/tests/basic-cat.csv')
     self.assertEqual(Category.objects.count(), 11)
    def add_arguments(self, parser):
        BaseCommand.add_arguments(self, parser)

        ahelp = ('TODO')
        parser.add_argument(
            '--reload', action='store_true', dest='use_reloader',
            default=False, help=ahelp)

        ahelp = (
            'The port that the http server should run on. It defaults to '
            '5000. This value can be set by the environment variable $PORT.')
        parser.add_argument(
            '--port', action='store', type=int, dest='port', default=None,
            help=ahelp)
        parser.add_argument(
            '--addr', action='store', type=str, dest='addr', default='0.0.0.0',
            help=ahelp)
Beispiel #53
0
 def create_parser(self, prog_name, subcommand):
     # Overwrite parser creation with a LaxOptionParser that will
     # ignore arguments it doesn't know, allowing us to pass those
     # along to the webassets command.
     # Hooking into run_from_argv() would be another thing to try
     # if this turns out to be problematic.
     parser = BaseCommand.create_parser(self, prog_name, subcommand)
     parser.__class__ = LaxOptionParser
     return parser
    def __init__(self, *args, **kwargs):
        class NiceContext(Context):
            """
            Same as the real context class, but override some methods in order to gain
            nice colored output.
            """
            def __init__(s, *args, **kwargs):
                kwargs['insert_debug_symbols'] = self.insert_debug_symbols

                Context.__init__(s, *args, **kwargs)

            def compile_media_callback(s, compress_tag, media_files):
                """
                When the compiler notifies us that compiling of this file begins.
                """
                if compress_tag:
                    print self.colored('Compiling media files from', 'yellow'),
                    print self.colored(' "%s" ' % compress_tag.path, 'green'),
                    print self.colored(' (line %s, column %s)" ' % (compress_tag.line, compress_tag.column), 'yellow')
                else:
                    print self.colored('Compiling media files', 'yellow')

                for m in media_files:
                    print self.colored('   * %s' % m, 'green')

            @contextmanager
            def time_operation(self, name):
                if self.verbosity >= 3:
                    begin = time.clock()
                    yield
                    end = time.clock()
                    print termcolor.colored(name, "blue"), (termcolor.colored("%.2fs" % (end - begin), "yellow"))
                else:
                    yield

            def compile_media_progress_callback(s, compress_tag, media_file, current, total, file_size):
                """
                Print progress of compiling media files.
                """
                print self.colored('       (%s / %s):' % (current, total), 'yellow'),
                print self.colored(' %s (%s bytes)' % (media_file, file_size), 'green')
        self.NiceContext = NiceContext

        BaseCommand.__init__(self, *args, **kwargs)
Beispiel #55
0
    def add_arguments(self, parser):
        BaseCommand.add_arguments(self, parser)

        ahelp = ('TODO')
        parser.add_argument(
            '--reload', action='store_true', dest='use_reloader',
            default=False, help=ahelp)
        ahelp = (
            'Port number to listen on. Defaults to the environment variable '
            '$PORT (if defined), or 8000.'
        )
        parser.add_argument(
            '--port', action='store', type=int, dest='port', default=None,
            help=ahelp)
        parser.add_argument(
            '--addr', action='store', type=str, dest='addr', default='0.0.0.0',
            help='The host/address to bind to (default: 0.0.0.0)')
        parser.add_argument(
            '--botworker', action='store_true',
            dest='botworker', default=False,
            help='Run botworker (for browser bots)')
    def __init__(self):
        BaseCommand.__init__(self)

        self.option_list += (
            make_option(
                '--days', '-d',
                help='Days of week (monday, tuesday, etc)'),
            make_option(
                '--occurrences', '-o',
                type='int',
                default=1,
                help='Occurrences: How many weeks ahead to exclude this day'),
            make_option(
                '--queues', '-q',
                help='Queues to include (default: all). Use queue slugs'),
            make_option(
                '--escalate-verbosely', '-x',
                action='store_true',
                default=False,
                help='Display a list of dates excluded'),
            )
Beispiel #57
0
    def validate_models(self):
        import django
        try:
            django_setup = django.setup
        except AttributeError:
            pass
        else:
            django_setup()
        s = io.StringIO()
        try:
            from django.core.management.validation import get_validation_errors
        except ImportError:
            from django.core.management.base import BaseCommand
            cmd = BaseCommand()
            try:
                # since django 1.5
                from django.core.management.base import OutputWrapper
                cmd.stdout = OutputWrapper(sys.stdout)
                cmd.stderr = OutputWrapper(sys.stderr)
            except ImportError:
                cmd.stdout, cmd.stderr = sys.stdout, sys.stderr

            cmd.check()
        else:
            num_errors = get_validation_errors(s, None)
            if num_errors:
                raise RuntimeError(
                    'One or more Django models did not validate:\n{0}'.format(
                        s.getvalue()))
Beispiel #58
0
	def __init__(self, *args, **kwargs):
		BaseCommand.__init__(self, *args, **kwargs)
		
		# Create cleaners
		self.readMoreCleaner = HTMLCleaner()
		self.contentCleaner = HTMLCleaner()
		
		for tag in ALLOWED_HTML_TAGS:
			attributes = []
			if tag in TAG_ATTRIBUTES:
				attributes = TAG_ATTRIBUTES[tag]
			self.readMoreCleaner.addAllowedTag(tag, attributes)

		for tag in ALLOWED_HTML_TAGS_STRICT:
			attributes = []
			if tag in TAG_ATTRIBUTES:
				attributes = TAG_ATTRIBUTES[tag]
			self.contentCleaner.addAllowedTag(tag, attributes)

		for key, value in TRANSFORM_TAGS.items():
			self.contentCleaner.addTransformationRule(key, value)
			self.readMoreCleaner.addTransformationRule(key, value)
Beispiel #59
0
 def __init__(self):
     BaseCommand.__init__(self)