コード例 #1
0
ファイル: depcheck.py プロジェクト: ilexius/pootle
def test_django():
    from django import VERSION, get_version

    if VERSION >= DJANGO_MINIMUM_REQUIRED_VERSION:
        return True, get_version()
    else:
        return False, get_version()
コード例 #2
0
    def run(self):
        sys.dont_write_bytecode = True
        from django import get_version
        django_release = re.search(r'^\d\.\d', get_version()).group(0)
        test_settings_exist = django_release in self.test_settings.keys()
        try:
            dj_ver = [int(n) for n in re.split(r'[.ab]', get_version())]
        except ValueError:
            # Pre-release Djangos must be testable!!!
            dj_too_old = False
        else:
            dj_too_old = dj_ver < [1, 4, 2]

        if test_settings_exist is False or dj_too_old:
            print("Please install Django 1.4.19 - 1.9 to run the test suite")
            exit(-1)

        os.environ['DJANGO_SETTINGS_MODULE'] = self.test_settings[
            django_release]
        try:
            from django.core.management import call_command
        except ImportError:
            print("Please install Django 1.4.2 - 1.9 to run the test suite")
            exit(-1)

        setup_django()

        call_command('test', 'likert_test_app', interactive=False, verbosity=1)

        try:
            import south
        except ImportError:
            pass
        else:
            call_command('test', 'suthern', interactive=False, verbosity=1)
コード例 #3
0
    def run(self):
        sys.dont_write_bytecode = True
        from django import get_version
        django_release = re.search(r'^\d\.\d', get_version()).group(0)
        if ((django_release not in self.test_settings.keys())
                or ([int(n) for n in re.split(r'[.ab]', get_version())]
                    < [1, 4, 2])):
            print("Please install Django 1.4.19 - 1.8 to run the test suite")
            exit(-1)
        os.environ['DJANGO_SETTINGS_MODULE'] = self.test_settings[
            django_release]
        try:
            from django.core.management import call_command
        except ImportError:
            print("Please install Django 1.4.19 - 1.8 to run the test suite")
            exit(-1)

        import django
        if hasattr(django, 'setup'):
            django.setup()

        call_command('test', 'pizzagigi', interactive=False, verbosity=1)
        call_command('test', 'forthewing', interactive=False, verbosity=1)

        try:
            import south
        except ImportError:
            pass
        else:
            call_command('test', 'suthern', interactive=False, verbosity=1)
コード例 #4
0
ファイル: fabfile.py プロジェクト: luzfcb/django-mtr-sync
def recreate():
    """Recreate new migrations from start and remove database"""

    project_prefixed_apps = []
    for app in PROJECT_APPS:
        project_prefixed_apps.append('{}.{}'.format(PROJECT_DIR, app))

    apps = APPS + project_prefixed_apps

    for app in apps:
        with lcd(os.path.join(*app.split('.'))):
            if django.get_version() >= '1.7':
                local('rm -f ./migrations/*.py')
                local('touch ./migrations/__init__.py')
            else:
                local('rm -f ./south_migrations/*.py')
                local('touch ./south_migrations/__init__.py')
    with lcd(PROJECT_DIR):
        if django.get_version() >= '1.7':
            local('rm -f db.sqlite3')
        else:
            local('rm -rf olddb.sqlite3')

    migrate()

    manage('createsuperuser --username app --email [email protected] --noinput')
    manage('changepassword app')
コード例 #5
0
ファイル: views.py プロジェクト: nuimk-proteus/django-slumber
 def test_instance_data_pizza(self):
     s = Pizza(name='S1', for_sale=True)
     s.save()
     response, json = self.do_get('/slumber_examples/Pizza/data/%s/' % s.pk)
     self.maxDiff = None
     expected = dict(
         _meta={'message': 'OK', 'status': 200, 'username': '******'},
         type=self.url('/slumber_examples/Pizza/'),
         identity=self.url('/slumber_examples/Pizza/data/1/'),
         display='S1',
         operations=dict(
             data=self.url('/slumber_examples/Pizza/data/1/'),
             delete=self.url('/slumber_examples/Pizza/delete/1/'),
             order=self.url('/slumber_examples/Pizza/order/1/'),
             update=self.url('/slumber_examples/Pizza/update/1/')),
         fields=dict(
             id=dict(data=s.pk, kind='value', type='django.db.models.fields.AutoField'),
             for_sale=dict(data=s.for_sale, kind='value', type='django.db.models.fields.BooleanField'),
             max_extra_toppings=dict(data=s.max_extra_toppings, kind='value', type='django.db.models.fields.IntegerField'),
             name=dict(data=s.name, kind='value', type='django.db.models.fields.CharField'),
             exclusive_to={'data': None, 'kind': 'object', 'type': self.url('/slumber_examples/Shop/')}),
         data_arrays=dict(
             prices=self.url('/slumber_examples/Pizza/data/%s/prices/' % s.pk)))
     if get_version() >= "1.8":
         expected['fields']['exclusive_to_id'] = expected['fields']['exclusive_to']
     elif get_version() >= "1.7":
         expected['data_arrays']['exclusive_to_id'] = self.url(
                 '/slumber_examples/Pizza/data/1/exclusive_to_id/')
     self.assertEquals(json, expected)
コード例 #6
0
    def test02_search(self):
        """
        Test full text searching in administration
        """
        request = REQ_FACTORY.get('/admin/admintests/', {'q': 'obsah'})
        # Second argument is admin_site, but it is not used in this test
        model_admin = MultilingualModelAdmin(AdminTests, None)
        kwargs = {'request': request,
                  'model': AdminTests,
                  'list_display': ('__str__', ),
                  'list_display_links': (),
                  'list_filter': (),
                  'date_hierarchy': None,
                  'search_fields': ('translations__title', ),
                  'list_select_related': False,
                  'list_per_page': 100,
                  'list_editable': (),
                  'model_admin': model_admin}
        # This argument was added in Django 1.4
        if get_version() >= '1.4':
            kwargs['list_max_show_all'] = 200

        cl = ChangeList(**kwargs)

        # This argument was added in Django 1.4
        if get_version() >= '1.4':
            queryset = cl.get_query_set(request)
        else:
            queryset = cl.get_query_set()

        self.assertEqual(len(queryset), 1)
        self.assertEqual(queryset[0].description, u'description ěščřžýáíé')
コード例 #7
0
    def test_schemafactory_get_unknown_build(self, mock_logging):
        schemas = DjangoSchemaFactory()
        version_string = django.get_version()
        self.assertFalse(version_string in schemas._schemas)

        # build schema
        schema = schemas.get(version_string, strict=False)()
        # get expected schema
        options = dict([(name.lower(), value) for (name, value) in
            inspect.getmembers(global_settings) if name.isupper()])
        project_options = dict([(name.lower(), value) for (name, value) in
            inspect.getmembers(get_project_settings()) if name.isupper()])
        # handle special case of ROOT_URLCONF which depends on the
        # project name
        root_urlconf = project_options['root_urlconf'].replace(
            '{{ project_name }}.', '')
        project_options['root_urlconf'] = root_urlconf

        options.update(project_options)
        expected = schemas.build(django.get_version(), options)()

        # compare schemas
        self.assert_schemas_equal(schema, expected)

        self.assertEqual(mock_logging.warn.call_args_list[0][0][0],
            "No schema registered for version '{0}'".format(version_string))
        self.assertEqual(mock_logging.warn.call_args_list[1][0][0],
            "Dynamically creating schema for version '{0}'".format(
                version_string))
コード例 #8
0
    def handle(self, *args, **options):
        # Delete ALL of the things.
        ProjectVersion.objects.filter(
            project__name__iexact='Django',
            version_number=django.get_version(),
        ).delete()
        Inheritance.objects.filter(
            parent__module__project_version__project__name__iexact='Django',
            parent__module__project_version__version_number=django.get_version(),
        ).delete()

        # Setup Project
        self.project_version = ProjectVersion.objects.create(
            project=Project.objects.get_or_create(name='Django')[0],
            version_number=django.get_version(),
        )

        self.klasses = {}
        self.attributes = {}
        self.klass_imports = {}

        # Set sources appropriate to this version
        self.sources = []
        for source in settings.CBV_SOURCES.keys():
            try:
                self.sources.append(importlib.import_module(source))
            except ImportError:
                pass

        print(t.red('Tree traversal'))
        for source in self.sources:
            self.process_member(source, source.__name__)
        self.create_inheritance()
        self.create_attributes()
コード例 #9
0
ファイル: depcheck.py プロジェクト: nrtest/wikitrans-pootle
def test_django():
    from django import VERSION, get_version

    if VERSION >= (1, 2, 0):
        return True, get_version()
    else:
        return False, get_version()
コード例 #10
0
ファイル: setup.py プロジェクト: leotop/django-likert-field
    def run(self):
        sys.dont_write_bytecode = True
        from django import get_version
        django_release = re.search(r'^\d\.\d', get_version()).group(0)
        if ((django_release not in self.test_settings.keys())
                or ([int(n) for n in re.split(r'[.ab]', get_version())]
                    < [1, 4, 2])):
            print("Please install Django 1.4.2 - 1.7 to run the test suite")
            exit(-1)

        os.environ['DJANGO_SETTINGS_MODULE'] = self.test_settings[
            django_release]
        try:
            from django.core.management import call_command
        except ImportError:
            print("Please install Django 1.4.2 - 1.7 to run the test suite")
            exit(-1)

        setup_django()
        # import django
        # try:
        #     django.setup()
        # except AttributeError:
        #     pass

        call_command('test', 'likert_test_app', interactive=False, verbosity=1)
コード例 #11
0
ファイル: sqlcreate.py プロジェクト: viikasgarg/funtime-1.0
    def handle(self, *args, **options):

        if django.get_version() >= "1.2":
            got_db_settings = self.set_db_settings(**options)
            if not got_db_settings:
                raise CommandError(
                    "You are using Django %s which requires to specify the db-router.\nPlease specify the router by adding --router=<routername> to this command." %
                    django.get_version())

        #print("%s %s %s %s" % (settings.DATABASE_ENGINE, settings.DATABASE_NAME, settings.DATABASE_USER, settings.DATABASE_PASSWORD))
        engine = settings.DATABASE_ENGINE
        dbname = settings.DATABASE_NAME
        dbuser = settings.DATABASE_USER
        dbpass = settings.DATABASE_PASSWORD
        dbhost = settings.DATABASE_HOST

        # django settings file tells you that localhost should be specified by leaving
        # the DATABASE_HOST blank
        if not dbhost:
            dbhost = 'localhost'

        if engine == 'mysql':
            sys.stderr.write(
                """-- WARNING!: https://docs.djangoproject.com/en/dev/ref/databases/#collation-settings
-- Please read this carefully! Collation will be set to utf8_bin to have case-sensitive data.
""")
            print(
                "CREATE DATABASE %s CHARACTER SET utf8 COLLATE utf8_bin;" %
                dbname)
            print(
                "GRANT ALL PRIVILEGES ON %s.* to '%s'@'%s' identified by '%s';" %
                (dbname, dbuser, dbhost, dbpass))
        elif engine == 'postgresql_psycopg2':
            if options.get('drop'):
                print("DROP DATABASE IF EXISTS %s;" % (dbname,))
                print("DROP USER IF EXISTS %s;" % (dbuser,))
            print(
                "CREATE USER %s WITH ENCRYPTED PASSWORD '%s' CREATEDB;" %
                (dbuser, dbpass))
            print(
                "CREATE DATABASE %s WITH ENCODING 'UTF-8' OWNER \"%s\";" %
                (dbname, dbuser))
            print(
                "GRANT ALL PRIVILEGES ON DATABASE %s TO %s;" %
                (dbname, dbuser))
        elif engine == 'sqlite3':
            sys.stderr.write(
                "-- manage.py syncdb will automatically create a sqlite3 database file.\n")
        else:
            # CREATE DATABASE is not SQL standard, but seems to be supported by
            # most.
            sys.stderr.write(
                "-- Don't know how to handle '%s' falling back to SQL.\n" %
                engine)
            print("CREATE DATABASE %s;" % dbname)
            print(
                "GRANT ALL PRIVILEGES ON DATABASE %s to %s" %
                (dbname, dbuser))
コード例 #12
0
ファイル: tests.py プロジェクト: bvox/django_openstack_auth
    def test_version_check(self):
        self.mox.StubOutWithMock(django, 'get_version')
        django.get_version().AndReturn('1.3')
        self.mox.ReplayAll()

        utils_compat = reload(utils)

        self.assertEqual(utils_compat.NOW, utils._now)
        self.assertEqual(utils_compat.parse_datetime, utils._parse_datetime)
コード例 #13
0
    def test_schemafactory_get_django(self):
        schemas = DjangoSchemaFactory()

        # build a django schema
        # get only django settings
        options = dict([(name, value) for (name, value) in
            inspect.getmembers(settings) if name.isupper()])
        schema = schemas.build(django.get_version(), options)
        # get known django schema
        # fail for unknown versions of django
        django_schema = schemas.get(django.get_version(), strict=True)

        self.assert_schemas_equal(schema(), django_schema())
コード例 #14
0
def main():
	settings.configure(
		INSTALLED_APPS = (
			'django.contrib.auth',
			'django.contrib.contenttypes',
			'django.contrib.admin',
			'django.contrib.sessions',
			'asymm_fields.tests.testapp',
			'asymm_fields'
		),
		DATABASE_ENGINE = 'django.db.backends.sqlite3',
		DATABASES = {
			'default': {
				'ENGINE': 'django.db.backends.sqlite3',
				'NAME': ':memory:',
			}
		},
		DEBUG = True,
		TEMPLATE_DEBUG = True,
	)
	if django.get_version() >= '1.7':
		django.setup() #@UndefinedVariable
	
	apps = ['asymm_fields']
	if django.get_version() >= '1.6':
		apps.append('asymm_fields.tests.testapp')
		apps.append('asymm_fields.tests')
	
	from django.core.management import call_command
	from django.test.utils import get_runner
	
	try:
		from django.contrib.auth import get_user_model
	except ImportError:
		USERNAME_FIELD = 'username'
	else:
		USERNAME_FIELD = get_user_model().USERNAME_FIELD
	
	class TestRunner(get_runner(settings)):
		def setup_databases(self, *args, **kwargs):
			result = super(TestRunner, self).setup_databases(*args, **kwargs)
			kwargs = {
				'interactive': False,
				'email': '*****@*****.**',
				USERNAME_FIELD: 'admin'
			}
			call_command('createsuperuser', **kwargs)
			return result
	
	failures = TestRunner(verbosity = 2, interactive = True).run_tests(apps)
	sys.exit(failures)
コード例 #15
0
def _is_django_10():
    """

    :return: is Django >= 1.10
    """
    try:
        from distutils.version import StrictVersion, LooseVersion
        import django
        try:
            return StrictVersion(django.get_version()) >= StrictVersion("1.10")
        except ValueError:
            return LooseVersion(django.get_version()) >= LooseVersion("1.10")
    except (ImportError, AttributeError):
        return False
コード例 #16
0
def get_reverse_field_name(model, field_name):
    if is_many_to_many(model, field_name) or is_one_to_one(model, field_name) or is_many_to_one(model, field_name):
        return getattr(model, field_name).field.related_query_name()
    elif StrictVersion(django.get_version()) >= StrictVersion('1.9') and is_reverse_many_to_many(model, field_name):
        return getattr(model, field_name).field.name
    elif StrictVersion(django.get_version()) >= StrictVersion('1.9') and is_reverse_many_to_one(model, field_name):
        return getattr(model, field_name).field.name
    elif is_reverse_one_to_one(model, field_name):
        return getattr(model, field_name).related.field.name
    elif (is_reverse_many_to_many(model, field_name) or is_reverse_one_to_one(model, field_name) or
            is_reverse_many_to_one(model, field_name)):
        return getattr(model, field_name).related.field.name
    else:
        raise FieldError('field {} is not relation'.format(field_name))
コード例 #17
0
 def setUp(self):
     super(GeneratedSettingsTestCase, self).setUp()
     self.expected_schema = schemas.get(
         django.get_version(), strict=True)()
     self.version = '.'.join(django.get_version().split('.')[:2]) + '.foo'
     mock_get_version = Mock(return_value=self.version)
     self.patch_get_version = patch(
         'django_configglue.tests.settings.django.get_version',
         mock_get_version)
     self.patch_get_version.start()
     self.mock_warn = Mock()
     self.patch_warn = patch(
         'django_configglue.schema.logging.warn', self.mock_warn)
     self.patch_warn.start()
コード例 #18
0
ファイル: runserver.py プロジェクト: mpetyx/mpetyx.com
        def inner_run():
            from django.conf import settings
            from django.utils import translation

            print "Validating models..."
            self.validate(display_num_errors=True)
            print "\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE)
            print "Development server is running at http://%s:%s/" % (addr, port)
            print "Quit the server with %s." % quit_command

            # django.core.management.base forces the locale to en-us. We should
            # set it up correctly for the first request (particularly important
            # in the "--noreload" case).
            translation.activate(settings.LANGUAGE_CODE)

            try:
                handler = AdminMediaHandler(WSGIHandler(), admin_media_path)
                run(addr, int(port), handler)
            except WSGIServerException, e:
                # Use helpful error messages instead of ugly tracebacks.
                ERRORS = {
                    13: "You don't have permission to access that port.",
                    98: "That port is already in use.",
                    99: "That IP address can't be assigned-to.",
                }
                try:
                    error_text = ERRORS[e.args[0].args[0]]
                except (AttributeError, KeyError):
                    error_text = str(e)
                sys.stderr.write(self.style.ERROR("Error: %s" % error_text) + '\n')
                # Need to use an OS exit because sys.exit doesn't work in a thread
                os._exit(1)
コード例 #19
0
def setup_requirements():

    print ('setting up requirements....')

    pathStr = 'requirements/base.txt'

    inputStr = 'Django==' + django.get_version() + '\npytz\n'

    write_file(pathStr, inputStr)

    for venv in range(4):

        pathStr = 'requirements/' + get_venv(venv) + '.txt'

        get_subprocess(['touch', pathStr])

        ps = subprocess.Popen(['echo', '-r base.txt'], shell=False,
                              stdout=subprocess.PIPE)

        subprocess.Popen(['tee', '-a', pathStr], shell=False,
                         stdin=ps.stdout)

        if venv == 1:

            write_file(pathStr, 'selenium==2.48.0\ncoverage\n')
コード例 #20
0
ファイル: runserver_plus.py プロジェクト: 2flcastro/ka-lite
 def inner_run():
     print "Validating models..."
     self.validate(display_num_errors=True)
     print "\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE)
     print "Development server is running at http://%s:%s/" % (addr, port)
     print "Using the Werkzeug debugger (http://werkzeug.pocoo.org/)"
     print "Quit the server with %s." % quit_command
     path = options.get('admin_media_path', '')
     if not path:
         admin_media_path = os.path.join(django.__path__[0], 'contrib/admin/static/admin')
         if os.path.isdir(admin_media_path):
             path = admin_media_path
         else:
             path = os.path.join(django.__path__[0], 'contrib/admin/media')
     handler = WSGIHandler()
     if USE_ADMINMEDIAHANDLER:
         handler = AdminMediaHandler(handler, path)
     if USE_STATICFILES:
         use_static_handler = options.get('use_static_handler', True)
         insecure_serving = options.get('insecure_serving', False)
         if use_static_handler and (settings.DEBUG or insecure_serving):
             handler = StaticFilesHandler(handler)
     if open_browser:
         import webbrowser
         url = "http://%s:%s/" % (addr, port)
         webbrowser.open(url)
     run_simple(addr, int(port), DebuggedApplication(handler, True),
                use_reloader=use_reloader, use_debugger=True, threaded=threaded)
コード例 #21
0
ファイル: statistics.py プロジェクト: msincan/juliabase
def about(request):
    """The “about” view.  It displays general superficial information about
    JuliaBase.  This view is more or less static – it shows only the components
    of JuliaBase and versioning information.

    Note that you needn't be logged in for accessing this.

    :param request: the current HTTP Request object

    :type request: HttpRequest

    :return:
      the HTTP response object

    :rtype: HttpResponse
    """
    context = {"title": _("With kind support of …"),
               "language_version": sys.version.split()[0],
               "matplotlib_version": matplotlib.__version__,
               "framework_version": django.get_version(),
               "juliabase_version": __version__
    }
    db_configuration = settings.DATABASES.get("default", {})
    db_backend = db_configuration.get("ENGINE")
    if db_backend == "django.db.backends.postgresql_psycopg2":
        cursor = connection.cursor()
        cursor.execute("SELECT version()")
        context["postgresql_version"] = cursor.fetchone()[0].split()[1]
    return render(request, "samples/about.html", context)
コード例 #22
0
 def label_for_value(self, value):
     key = self.rel.get_related_field().name
     obj = self.rel.to._default_manager.get(**{key: value})
     if django.get_version() >= "1.4":
         return Truncator(obj).words(14, truncate='...')
     else:
         return truncate_words(obj, 14)
コード例 #23
0
ファイル: base.py プロジェクト: 0038lana/Test-Task
 def get_version(self):
     """
     Return the Django version, which should be correct for all built-in
     Django commands. User-supplied commands can override this method to
     return their own version.
     """
     return django.get_version()
コード例 #24
0
ファイル: runtornado.py プロジェクト: stanfeldman/47finds
        def inner_run():
            from django.conf import settings
            from django.utils import translation
            print "Validating models..."
            self.validate(display_num_errors=True)
            print "\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE)
            print "Server is running at http://%s:%s/" % (addr, port)
            print "Quit the server with %s." % quit_command

            # django.core.management.base forces the locate to en-us. We
            # should set it up correctly for the first request
            # (particularly important in the not "--reload" case).
            translation.activate(settings.LANGUAGE_CODE)

            try:
                application = tornado.web.Application(
                	[(r".*", DjangoHandler),],
                	socket_io_port = int(port)
                )
                http_server = tornadio.server.SocketServer(application)

                if hasattr(settings, 'TORNADO_STARTUP') :
                    from django.utils.importlib import import_module
                    for obj in settings.TORNADO_STARTUP :
                        # TODO - check to see if string or object
                        idx = obj.rindex('.')
                        func = getattr(import_module(obj[:idx]), obj[idx+1:])
                        func()

                ioloop.IOLoop.instance().start()
            except KeyboardInterrupt:
                if shutdown_message:
                    print shutdown_message
                sys.exit(0)
コード例 #25
0
   def inner_run():  
       from django.conf import settings  
       from django.utils import translation  
       print "\nValidating models..."  
       self.validate(display_num_errors=True)  
       print "\nDjango version %s, using settings %r" % (django.get_version(), settings.SETTINGS_MODULE)  
       print "Development server is running at http://%s:%s/" % (addr, port)  
       print "Quit the server with %s." % quit_command  
         
       # django.core.management.base forces the locale to en-us. We should  
       # set it up correctly for the first request (particularly important  
       # in the "--noreload" case).  
       translation.activate(settings.LANGUAGE_CODE)  
         
       try:  
            
           handler = StaticFilesHandler(WSGIHandler())  
           cherrypy.config.update({  
                   'server.socket_host': addr,  
                   'server.socket_port': int(port),  
                   'engine.autoreload_on':  use_reloader  
               })  
 
           cherrypy.tree.graft(handler, '/')  
 
           cherrypy.engine.start()  
           cherrypy.engine.block()  
       finally:  
           if shutdown_message:  
               print shutdown_message  
           cherrypy.engine.exit()  
コード例 #26
0
ファイル: test_selenium.py プロジェクト: Yixf-Self/weblate
    def setUpClass(cls):
        if DO_SELENIUM:
            cls.caps['name'] = 'Weblate CI build'
            # Fill in Travis details in caps
            if 'TRAVIS_JOB_NUMBER' in os.environ:
                cls.caps['tunnel-identifier'] = os.environ['TRAVIS_JOB_NUMBER']
                cls.caps['build'] = os.environ['TRAVIS_BUILD_NUMBER']
                cls.caps['tags'] = [
                    'python-{}'.format(os.environ['TRAVIS_PYTHON_VERSION']),
                    'django-{}'.format(django.get_version()),
                    'CI'
                ]

            # Use Sauce connect
            cls.username = os.environ['SAUCE_USERNAME']
            cls.key = os.environ['SAUCE_ACCESS_KEY']
            cls.sauce_auth = b64encode(
                '{}:{}'.format(cls.username, cls.key).encode('utf-8')
            )
            cls.driver = webdriver.Remote(
                desired_capabilities=cls.caps,
                command_executor="http://{0}:{1}@{2}/wd/hub".format(
                    cls.username,
                    cls.key,
                    'ondemand.saucelabs.com',
                )
            )
            cls.driver.implicitly_wait(10)
            cls.actions = webdriver.ActionChains(cls.driver)
            jobid = cls.driver.session_id
            print(
                'Sauce Labs job: https://saucelabs.com/jobs/{}'.format(jobid)
            )
        super(SeleniumTests, cls).setUpClass()
コード例 #27
0
ファイル: system.py プロジェクト: abbacode/avaloria
    def func(self):
        "Show the version"
        try:
            import south
            sversion = "{wSouth{n %s" % south.__version__
        except ImportError:
            sversion = "{wSouth{n <not installed>"

        string = """
         {cEvennia{n %s{n
         MUD/MUX/MU* development system

         {wLicence{n Artistic Licence/GPL
         {wWeb{n http://www.evennia.com
         {wIrc{n #evennia on FreeNode
         {wForum{n http://www.evennia.com/discussions
         {wMaintainer{n (2010-)   Griatch (griatch AT gmail DOT com)
         {wMaintainer{n (2006-10) Greg Taylor

         {wOS{n %s
         {wPython{n %s
         {wDjango{n %s
         {wTwisted{n %s
         %s
        """ % (utils.get_evennia_version(),
               os.name,
               sys.version.split()[0],
               django.get_version(),
               twisted.version.short(),
               sversion)
        self.caller.msg(string)
コード例 #28
0
ファイル: harvest.py プロジェクト: phelios/lettuce
    def create_parser(self, prog_name, subcommand):
        parser = super(Command, self).create_parser(prog_name, subcommand)

        # Ensure backward compatibility with Django, removing -v option if conflict found.
        if parser.has_option('-v'):
            parser.remove_option('-v')

        help_text = ('Verbosity level; 0=no output, 1=only dots, 2=only '
                     'scenario names, 3=normal output, 4=normal output '
                     '(colorful, deprecated)')
        parser.add_option('-v', '--verbosity',
                          action='store',
                          dest='verbosity',
                          default='3',
                          type='choice',
                          choices=map(str, range(5)),
                          help=help_text)
        if StrictVersion(django.get_version()) < StrictVersion('1.7'):
            # Django 1.7 introduces the --no-color flag. We must add the flag
            # to be compatible with older django versions
            parser.add_option('--no-color',
                              action='store_true',
                              dest='no_color',
                              default=False,
                              help="Don't colorize the command output.")
        return parser
コード例 #29
0
def create_admin_media_links():
    """
    This traverses to src/web/media and tries to create a symbolic
    link to the django media files from within the MEDIA_ROOT.
    These are files we normally don't
    want to mess with (use templates to customize the admin
    look). Linking is needed since the Twisted webserver otherwise has no
    notion of where the default files are - and we cannot hard-code it
    since the django install may be at different locations depending
    on system.
    """
    import django, os

    if django.get_version() < 1.4:
        dpath = os.path.join(django.__path__[0], 'contrib', 'admin', 'media')
    else:
        dpath = os.path.join(django.__path__[0], 'contrib', 'admin', 'static', 'admin')
    apath = os.path.join(settings.ADMIN_MEDIA_ROOT)
    if os.path.isdir(apath):
        print " ADMIN_MEDIA_ROOT already exists. Ignored."
        return
    if os.name == 'nt':
        print " Admin-media files copied to ADMIN_MEDIA_ROOT (Windows mode)."
        os.mkdir(apath)
        os.system('xcopy "%s" "%s" /e /q /c' % (dpath, apath))
    if os.name == 'posix':
        try:
            os.symlink(dpath, apath)
            print " Admin-media symlinked to ADMIN_MEDIA_ROOT."
        except OSError, e:
            print " There was an error symlinking Admin-media to ADMIN_MEDIA_ROOT:\n  %s\n   -> \n  %s\n  (%s)\n  If you see issues, link manually." % (dpath, apath, e)
コード例 #30
0
def about_view(request):
    print "----> "
    print request.session.session_key
    version = django.get_version()
    mensaje = "Esto es un mensaje desde mi vista"
    ctx = {'msg':mensaje,'version':version}
    return render_to_response('account/about.html',ctx,context_instance=RequestContext(request))
コード例 #31
0
"""Templatetags for the image_collection app."""
from distutils.version import StrictVersion

from django import get_version, template

from ..models import ImageCollection


register = template.Library()


django_version = get_version()
if StrictVersion(django_version) < StrictVersion('1.9'):
    filename = 'file_name'
else:
    filename = 'filename'

tag_kwargs = {
    'takes_context': True,
    filename: 'image_collection/tags/bs3_carousel.html'
}


@register.inclusion_tag(**tag_kwargs)
def render_bs3_carousel(context, identifier):
    """Renders an image collection as Bootstrap 3 carousel."""
    try:
        collection = ImageCollection.objects.get(identifier=identifier)
    except ImageCollection.DoesNotExist:
        collection = None
    context.update({'collection': collection})
コード例 #32
0
    from pygments.formatters import HtmlFormatter
    HAS_PYGMENTS = True
except ImportError:
    HAS_PYGMENTS = False

register = template.Library()


@stringfilter
def parse_template(value):
    return mark_safe(Template(value).render(Context()))


parse_template.is_safe = True

if django.get_version() >= "1.4":
    register.filter(parse_template, is_safe=True)
else:
    parse_template.is_safe = True
    register.filter(parse_template)


class CodeNode(Node):
    def __init__(self, language, nodelist, name=''):
        self.language = Variable(language)
        self.nodelist = nodelist
        if name:
            self.name = Variable(name)
        else:
            self.name = None
コード例 #33
0
#
# -*- coding: utf-8 -*-
#

from django import get_version
from distutils.version import LooseVersion

if (LooseVersion(get_version()) < LooseVersion('1.8')):
    from optparse import make_option

    options_list = (
        make_option('-f', '--logfile',
            action='store',
            dest='logfile',
            default=None,
            help='Tells server where to log information. Leaving this blank logs to stderr'
        ),
        make_option('-l', '--loglevel',
            action='store',
            dest='loglevel',
            default='info',
            help='Tells server what level of information to log'
        ),
    )
else:
    options_list = (
        dict(args=('-f', '--logfile'),
            kw=dict(
                action='store',
                dest='logfile',
                default=None,
コード例 #34
0
ファイル: views.py プロジェクト: aldenjenkins/ThiccGaming
def is_spam_akismet(request, form, url):
    """
    Identifies form data as being spam, using the http://akismet.com
    service. The Akismet API key should be specified in the
    ``AKISMET_API_KEY`` setting. This function is the default spam
    handler defined in the ``SPAM_FILTERS`` setting.

    The name, email, url and comment fields are all guessed from the
    form fields:

    * name: First field labelled "Name", also taking i18n into account.
    * email: First ``EmailField`` field.
    * url: First ``URLField`` field.
    * comment: First field with a ``Textarea`` widget.

    If the actual comment can't be extracted, spam checking is passed.

    The referrer field expects a hidden form field to pass the referrer
    through, since the HTTP_REFERER will be the URL the form is posted
    from. The hidden referrer field is made available by default with
    the ``{% fields_for %}`` templatetag used for rendering form fields.
    """
    if not settings.AKISMET_API_KEY:
        return False
    protocol = "http" if not request.is_secure() else "https"
    host = protocol + "://" + request.get_host()
    data = {
        "blog": host,
        "user_ip": ip_for_request(request),
        "user_agent": request.META.get("HTTP_USER_AGENT", ""),
        "referrer": request.POST.get("referrer", ""),
        "permalink": host + url,
        "comment_type": "comment" if "comment" in request.POST else "form",
    }
    for name, field in form.fields.items():
        data_field = None
        if field.label and field.label.lower() in ("name", _("Name").lower()):
            data_field = "comment_author"
        elif isinstance(field, EmailField):
            data_field = "comment_author_email"
        elif isinstance(field, URLField):
            data_field = "comment_author_url"
        elif isinstance(field.widget, Textarea):
            data_field = "comment_content"
        if data_field and not data.get(data_field):
            cleaned_data = form.cleaned_data.get(name)
            try:
                data[data_field] = cleaned_data.encode('utf-8')
            except UnicodeEncodeError:
                data[data_field] = cleaned_data
    if not data.get("comment_content"):
        return False
    api_url = ("http://%s.rest.akismet.com/1.1/comment-check" %
               settings.AKISMET_API_KEY)
    versions = (django.get_version(), mezzanine.__version__)
    headers = {"User-Agent": "Django/%s | Mezzanine/%s" % versions}
    try:
        response = urlopen(
            Request(api_url,
                    urlencode(data).encode('utf-8'), headers)).read()
    except Exception:
        return False

    # Python 3 returns response as a bytestring, Python 2 as a regular str
    return response in (b'true', 'true')
コード例 #35
0
ファイル: mixins.py プロジェクト: mithjem/wagtail-tag-manager
import django
from django.db import models
from modelcluster.fields import ParentalManyToManyField
from modelcluster.models import ClusterableModel
from wagtail.admin.edit_handlers import FieldPanel, MultiFieldPanel, PublishingPanel

from wagtail_tag_manager.models import Tag
from wagtail_tag_manager.widgets import (
    HorizontalCheckboxSelectMultiple as CheckboxSelectMultiple, )

__version__ = django.get_version()
if __version__.startswith("2"):
    from django.utils.translation import ugettext_lazy as _
else:
    from django.utils.translation import gettext_lazy as _


class TagMixin(ClusterableModel):
    wtm_tags = ParentalManyToManyField(
        Tag,
        blank=True,
        related_name="pages",
        verbose_name=_("Tags"),
        help_text=_("The tags to include when this page is loaded."),
    )
    wtm_include_children = models.BooleanField(
        default=False,
        verbose_name=_("Include children"),
        help_text=_("Also include these tags on all children of this page."),
    )
コード例 #36
0
 def override_settings(*args, **kwargs):
     return unittest.skipIf(django.get_version().startswith('1.3'),
                            "Django < 1.4 doesn't have override_settings")
コード例 #37
0
        def inner_run():
            from django.conf import settings

            import os
            import time
            import hotshot
            USE_CPROFILE = options.get('use_cprofile', False)
            USE_LSPROF = options.get('use_lsprof', False)
            if USE_LSPROF:
                USE_CPROFILE = True
            if USE_CPROFILE:
                try:
                    import cProfile
                    USE_CPROFILE = True
                except ImportError:
                    print "cProfile disabled, module cannot be imported!"
                    USE_CPROFILE = False
            if USE_LSPROF and not USE_CPROFILE:
                raise SystemExit(
                    "Kcachegrind compatible output format required cProfile from Python 2.5"
                )
            prof_path = options.get('prof_path', '/tmp')

            def make_profiler_handler(inner_handler):
                def handler(environ, start_response):
                    path_info = environ['PATH_INFO']
                    # normally /media/ is STATIC_URL, but in case still check it in case it's differently
                    # should be hardly a penalty since it's an OR expression.
                    # TODO: fix this to check the configuration settings and not make assumpsions about where media are on the url
                    if no_media and (path_info.startswith('/media')
                                     or path_info.startswith(
                                         settings.STATIC_URL)):
                        return inner_handler(environ, start_response)
                    path_name = path_info.strip("/").replace('/',
                                                             '.') or "root"
                    profname = "%s.%s.prof" % (path_name,
                                               datetime.now().isoformat())
                    profname = os.path.join(prof_path, profname)
                    if USE_CPROFILE:
                        prof = cProfile.Profile()
                    else:
                        prof = hotshot.Profile(profname)
                    start = datetime.now()
                    try:
                        return prof.runcall(inner_handler, environ,
                                            start_response)
                    finally:
                        # seeing how long the request took is important!
                        elap = datetime.now() - start
                        elapms = elap.seconds * 1000.0 + elap.microseconds / 1000.0
                        if USE_LSPROF:
                            kg = KCacheGrind(prof)
                            kg.output(file(profname, 'w'))
                        elif USE_CPROFILE:
                            prof.dump_stats(profname)
                        profname2 = "%s.%06dms.%s.prof" % (
                            path_name, elapms, datetime.now().isoformat())
                        profname2 = os.path.join(prof_path, profname2)
                        os.rename(profname, profname2)

                return handler

            print "Validating models..."
            self.validate(display_num_errors=True)
            print "\nDjango version %s, using settings %r" % (
                django.get_version(), settings.SETTINGS_MODULE)
            print "Development server is running at http://%s:%s/" % (addr,
                                                                      port)
            print "Quit the server with %s." % quit_command
            try:
                path = admin_media_path or django.__path__[
                    0] + '/contrib/admin/media'
                handler = make_profiler_handler(
                    AdminMediaHandler(WSGIHandler(), path))
                run(addr, int(port), handler)
            except WSGIServerException, e:
                # Use helpful error messages instead of ugly tracebacks.
                ERRORS = {
                    13: "You don't have permission to access that port.",
                    98: "That port is already in use.",
                    99: "That IP address can't be assigned-to.",
                }
                try:
                    error_text = ERRORS[e.args[0].args[0]]
                except (AttributeError, KeyError):
                    error_text = str(e)
                sys.stderr.write(
                    self.style.ERROR("Error: %s" % error_text) + '\n')
                # Need to use an OS exit because sys.exit doesn't work in a thread
                os._exit(1)
コード例 #38
0
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_tables2',
    'bootstrap3',
    'dbbackup',
    'viz',
    'rules',
    'suricata',
    'accounts',
    'rest_framework',
    'rest_framework.authtoken',
    'django_filters',
    'webpack_loader',
)

if LooseVersion(get_version()) < LooseVersion('1.7'):
    INSTALLED_APPS += ('south', )

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'scirius.loginrequired.LoginRequiredMiddleware',
    'scirius.utils.TimezoneMiddleware',
]

TEMPLATES = [
コード例 #39
0
        def inner_run():
            print("Performing system checks...\n")
            if hasattr(self, 'check'):
                self.check(display_num_errors=True)
            else:
                self.validate(display_num_errors=True)
            if HAS_MIGRATIONS:
                try:
                    self.check_migrations()
                except ImproperlyConfigured:
                    pass
            print("\nDjango version %s, using settings %r" %
                  (django.get_version(), settings.SETTINGS_MODULE))
            print("Development server is running at %s" % (bind_url, ))
            print("Using the Werkzeug debugger (http://werkzeug.pocoo.org/)")
            print("Quit the server with %s." % quit_command)
            path = options.get('admin_media_path', '')
            if not path:
                admin_media_path = os.path.join(django.__path__[0],
                                                'contrib/admin/static/admin')
                if os.path.isdir(admin_media_path):
                    path = admin_media_path
                else:
                    path = os.path.join(django.__path__[0],
                                        'contrib/admin/media')
            handler = WSGIHandler()
            if USE_ADMINMEDIAHANDLER:
                handler = AdminMediaHandler(handler, path)
            if USE_STATICFILES:
                use_static_handler = options.get('use_static_handler', True)
                insecure_serving = options.get('insecure_serving', False)
                if use_static_handler and (settings.DEBUG or insecure_serving):
                    handler = StaticFilesHandler(handler)
            if open_browser:
                import webbrowser
                webbrowser.open(bind_url)
            if cert_path:
                """
                OpenSSL is needed for SSL support.

                This will make flakes8 throw warning since OpenSSL is not used
                directly, alas, this is the only way to show meaningful error
                messages. See:
                http://lucumr.pocoo.org/2011/9/21/python-import-blackbox/
                for more information on python imports.
                """
                try:
                    import OpenSSL  # NOQA
                except ImportError:
                    raise CommandError(
                        "Python OpenSSL Library is "
                        "required to use runserver_plus with ssl support. "
                        "Install via pip (pip install pyOpenSSL).")

                dir_path, cert_file = os.path.split(cert_path)
                if not dir_path:
                    dir_path = os.getcwd()
                root, ext = os.path.splitext(cert_file)
                certfile = os.path.join(dir_path, root + ".crt")
                keyfile = os.path.join(dir_path, root + ".key")
                try:
                    from werkzeug.serving import make_ssl_devcert
                    if os.path.exists(certfile) and \
                            os.path.exists(keyfile):
                        ssl_context = (certfile, keyfile)
                    else:  # Create cert, key files ourselves.
                        ssl_context = make_ssl_devcert(os.path.join(
                            dir_path, root),
                                                       host='localhost')
                except ImportError:
                    print(
                        "Werkzeug version is less than 0.9, trying adhoc certificate."
                    )
                    ssl_context = "adhoc"

            else:
                ssl_context = None

            if use_reloader and settings.USE_I18N:
                try:
                    from django.utils.autoreload import gen_filenames
                except ImportError:
                    pass
                else:
                    extra_files.extend(
                        filter(lambda filename: filename.endswith('.mo'),
                               gen_filenames()))

            run_simple(
                self.addr,
                int(self.port),
                DebuggedApplication(handler, True),
                use_reloader=use_reloader,
                use_debugger=True,
                extra_files=extra_files,
                reloader_interval=reloader_interval,
                threaded=threaded,
                ssl_context=ssl_context,
            )
コード例 #40
0
    def get_traceback_data(self):
        """Return a dictionary containing traceback information."""
        if self.exc_type and issubclass(self.exc_type, TemplateDoesNotExist):
            self.template_does_not_exist = True
            self.postmortem = self.exc_value.chain or [self.exc_value]

        frames = self.get_traceback_frames()
        for i, frame in enumerate(frames):
            if 'vars' in frame:
                frame_vars = []
                for k, v in frame['vars']:
                    v = pprint(v)
                    # The force_escape filter assume unicode, make sure that works
                    if isinstance(v, six.binary_type):
                        v = v.decode(
                            'utf-8',
                            'replace')  # don't choke on non-utf-8 input
                    # Trim large blobs of data
                    if len(v) > 4096:
                        v = '%s... <trimmed %d bytes string>' % (v[0:4096],
                                                                 len(v))
                    frame_vars.append((k, force_escape(v)))
                frame['vars'] = frame_vars
            frames[i] = frame

        unicode_hint = ''
        if self.exc_type and issubclass(self.exc_type, UnicodeError):
            start = getattr(self.exc_value, 'start', None)
            end = getattr(self.exc_value, 'end', None)
            if start is not None and end is not None:
                unicode_str = self.exc_value.args[1]
                unicode_hint = smart_text(
                    unicode_str[max(start - 5, 0):min(end +
                                                      5, len(unicode_str))],
                    'ascii',
                    errors='replace')
        from django import get_version

        if self.request is None:
            user_str = None
        else:
            try:
                user_str = force_text(self.request.user)
            except Exception:
                # request.user may raise OperationalError if the database is
                # unavailable, for example.
                user_str = '[unable to retrieve the current user]'

        c = {
            'is_email': self.is_email,
            'unicode_hint': unicode_hint,
            'frames': frames,
            'request': self.request,
            'filtered_POST': self.filter.get_post_parameters(self.request),
            'user_str': user_str,
            'settings': get_safe_settings(),
            'sys_executable': sys.executable,
            'sys_version_info': '%d.%d.%d' % sys.version_info[0:3],
            'server_time': timezone.now(),
            'django_version_info': get_version(),
            'sys_path': sys.path,
            'template_info': self.template_info,
            'template_does_not_exist': self.template_does_not_exist,
            'postmortem': self.postmortem,
        }
        # Check whether exception info is available
        if self.exc_type:
            c['exception_type'] = self.exc_type.__name__
        if self.exc_value:
            c['exception_value'] = smart_text(self.exc_value, errors='replace')
        if frames:
            c['lastframe'] = frames[-1]
        return c
コード例 #41
0
ファイル: views.py プロジェクト: ylada/django-notifications
from django import get_version
from django.contrib.auth.decorators import login_required
from django.forms import model_to_dict
from django.shortcuts import get_object_or_404, redirect
from django.utils.decorators import method_decorator
from django.views.decorators.cache import never_cache
from django.views.generic import ListView
from notifications import settings
from notifications.settings import get_config
from notifications.utils import id2slug, slug2id
from swapper import load_model

Notification = load_model('notifications', 'Notification')

if StrictVersion(get_version()) >= StrictVersion('1.7.0'):
    from django.http import JsonResponse  # noqa
else:
    # Django 1.6 doesn't have a proper JsonResponse
    import json
    from django.http import HttpResponse  # noqa

    def date_handler(obj):
        return obj.isoformat() if hasattr(obj, 'isoformat') else obj

    def JsonResponse(data):  # noqa
        return HttpResponse(json.dumps(data, default=date_handler),
                            content_type="application/json")


class NotificationViewList(ListView):
コード例 #42
0
ファイル: settings.py プロジェクト: vituocgia/boxme-api
import os
import sys

from distutils.version import StrictVersion
import django
django_version_string = django.get_version()
if django_version_string.startswith('2.1.dev'):
    DJANGO_VERSION = StrictVersion('2.1')
else:
    DJANGO_VERSION = StrictVersion(django.get_version())
DJANGO_20 = StrictVersion('2.0')
DJANGO_11 = StrictVersion('1.11')
DJANGO_19 = StrictVersion('1.9')
DJANGO_18 = StrictVersion('1.8')

sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

ADMINS = (
    ('*****@*****.**', 'Mr. Test'),
)

ALLOWED_HOSTS = [u'example.com']

SITE_ID = 1

BASE_PATH = os.path.abspath(os.path.dirname(__file__))

MEDIA_ROOT = os.path.normpath(os.path.join(BASE_PATH, 'media'))

DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = 'bmga.db'
コード例 #43
0
# -*- coding: utf-8 -*-
from django import get_version

VERSION = (1, 0, 0, 'alpha', 2)

__version__ = get_version(VERSION)
コード例 #44
0
from galerie_cms_integration.models import Loc, Groupe
from django.contrib.gis.geos import GEOSGeometry, Point


l = Loc()

l.geolocalisation = Point(12.4604, 43.9420)

l.save()
Loc.objects.all()


c=Loc.objects.filter(geolocalisation='Point(12.4604 43.9420)')
c.delete()

d=Loc.objects.all()
d.delete()

l.geolocalisation=GEOSGeometry('POINT(%s %s)' % (1,1))


import django
django.get_version()
from django.contrib.gis import geos
geos.geos_version()
コード例 #45
0
logger = logging.getLogger(__name__)

# inspired by http://github.com/tobi/delayed_job
#

# Django 1.6 renamed Manager's get_query_set to get_queryset, and the old
# function will be removed entirely in 1.8. We work back to 1.4, so use a
# metaclass to not worry about it.
# from https://github.com/mysociety/mapit/blob/master/mapit/djangopatch.py#L14-L42

try:
    from django.utils import six
except ImportError:  # Django < 1.4.2
    import six

if django.get_version() < '1.6':

    class GetQuerySetMetaclass(type):
        def __new__(cls, name, bases, attrs):
            new_class = super(GetQuerySetMetaclass,
                              cls).__new__(cls, name, bases, attrs)

            old_method_name = 'get_query_set'
            new_method_name = 'get_queryset'
            for base in inspect.getmro(new_class):
                old_method = base.__dict__.get(old_method_name)
                new_method = base.__dict__.get(new_method_name)

                if not new_method and old_method:
                    setattr(base, new_method_name, old_method)
                if not old_method and new_method:
コード例 #46
0
class TestHTMLEmail(TestCase):
    EMAIL_ATTRS = {
        'subject': 'test email',
        'to': ['*****@*****.**'],
        'from_email': '*****@*****.**',
        'template_name': 'tests/test_HTMLEmail_template.html',
    }

    def setUp(self):
        class TestHTMLEmail(HTMLEmail):
            subject = self.EMAIL_ATTRS['subject']
            to = self.EMAIL_ATTRS['to']
            from_email = self.EMAIL_ATTRS['from_email']
            template_name = self.EMAIL_ATTRS['template_name']

            def get_context_data(self, **kwargs):
                kwargs = super(TestHTMLEmail, self).get_context_data(**kwargs)
                kwargs.update({
                    'title': 'test title',
                    'content': 'test content',
                })
                return kwargs

        self.TestHTMLEmail = TestHTMLEmail

    def create_and_send_a_message(self, **kwargs):
        email_callable = self.TestHTMLEmail.as_callable(**kwargs)
        email_callable()

    def test_mail_is_sent(self):
        self.create_and_send_a_message()
        self.assertEqual(len(mail.outbox), 1)

    def test_mail_has_html_body(self):
        self.create_and_send_a_message()
        message = mail.outbox[0]
        self.assertTrue(message.alternatives)
        self.assertEqual(message.alternatives[0][1], 'text/html')

    @unittest.skipIf(
        django.get_version().startswith('1.3'),
        "Django < 1.4 doesn't allow assertTemplateUsed as a context manager")
    def test_template_used(self):
        with self.assertTemplateUsed(
                template_name=self.EMAIL_ATTRS['template_name']):
            self.create_and_send_a_message()

    def test_html_body(self):
        self.create_and_send_a_message()
        message = mail.outbox[0]
        html_body = message.alternatives[0][0]
        try:
            self.assertInHTML('<h1>test title</h1>', html_body)
            self.assertInHTML('<p>test content</p>', html_body)
        except AttributeError:  # support for < django 1.5
            self.assertIn('<h1>test title</h1>', html_body)
            self.assertIn('<p>test content</p>', html_body)

    def test_plain_body(self):
        self.create_and_send_a_message()
        message = mail.outbox[0]
        self.assertIn('test title', message.body)
        self.assertIn('test content', message.body)
        self.assertNotIn('<h1>', message.body)
        self.assertNotIn('<p>', message.body)
コード例 #47
0
ファイル: __init__.py プロジェクト: ytothej92/django
    def execute(self):
        """
        Given the command-line arguments, figure out which subcommand is being
        run, create a parser appropriate to that command, and run it.
        """
        try:
            subcommand = self.argv[1]
        except IndexError:
            subcommand = 'help'  # Display help if no arguments were given.

        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        parser = CommandParser(None,
                               usage="%(prog)s subcommand [options] [args]",
                               add_help=False)
        parser.add_argument('--settings')
        parser.add_argument('--pythonpath')
        parser.add_argument('args', nargs='*')  # catch-all
        try:
            options, args = parser.parse_known_args(self.argv[2:])
            handle_default_options(options)
        except CommandError:
            pass  # Ignore any option errors at this point.

        try:
            settings.INSTALLED_APPS
        except ImproperlyConfigured as exc:
            self.settings_exception = exc
        except ImportError as exc:
            self.settings_exception = exc

        if settings.configured:
            # Start the auto-reloading dev server even if the code is broken.
            # The hardcoded condition is a code smell but we can't rely on a
            # flag on the command class because we haven't located it yet.
            if subcommand == 'runserver' and '--noreload' not in self.argv:
                try:
                    autoreload.check_errors(django.setup)()
                except Exception:
                    # The exception will be raised later in the child process
                    # started by the autoreloader. Pretend it didn't happen by
                    # loading an empty list of applications.
                    apps.all_models = defaultdict(OrderedDict)
                    apps.app_configs = OrderedDict()
                    apps.apps_ready = apps.models_ready = apps.ready = True

                    # Remove options not compatible with the built-in runserver
                    # (e.g. options for the contrib.staticfiles' runserver).
                    # Changes here require manually testing as described in
                    # #27522.
                    _parser = self.fetch_command('runserver').create_parser(
                        'django', 'runserver')
                    _options, _args = _parser.parse_known_args(self.argv[2:])
                    for _arg in _args:
                        self.argv.remove(_arg)

            # In all other cases, django.setup() is required to succeed.
            else:
                django.setup()

        self.autocomplete()

        if subcommand == 'help':
            if '--commands' in args:
                sys.stdout.write(
                    self.main_help_text(commands_only=True) + '\n')
            elif not options.args:
                sys.stdout.write(self.main_help_text() + '\n')
            else:
                self.fetch_command(options.args[0]).print_help(
                    self.prog_name, options.args[0])
        # Special-cases: We want 'django-admin --version' and
        # 'django-admin --help' to work, for backwards compatibility.
        elif subcommand == 'version' or self.argv[1:] == ['--version']:
            sys.stdout.write(django.get_version() + '\n')
        elif self.argv[1:] in (['--help'], ['-h']):
            sys.stdout.write(self.main_help_text() + '\n')
        else:
            self.fetch_command(subcommand).run_from_argv(self.argv)
コード例 #48
0
import os
import sys
from django import get_version

myPath = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, myPath)

VERSION = (0, 7, 15)

default_app_config = 'django_q.apps.DjangoQConfig'

# root imports will slowly be deprecated.
# please import from the relevant sub modules
if get_version().split('.')[1][0] != '9':
    from .tasks import async, schedule, result, result_group, fetch, fetch_group, count_group, delete_group, queue_size
    from .models import Task, Schedule, Success, Failure
    from .cluster import Cluster
    from .status import Stat
    from .brokers import get_broker

__all__ = ['conf', 'cluster', 'models', 'tasks']
コード例 #49
0
  import pyparsing
except ImportError:
  sys.stderr.write("[REQUIRED] Unable to import the 'pyparsing' module, do you have pyparsing module installed for python %s?\n" % py_version)
  required += 1


# Test for django-tagging
try:
  import tagging
except ImportError:
  sys.stderr.write("[REQUIRED] Unable to import the 'tagging' module, do you have django-tagging installed for python %s?\n" % py_version)
  required += 1


if django and django.VERSION[:2] < (1,4):
  sys.stderr.write("[REQUIRED] You have django version %s installed, but version 1.4 or greater is required\n" % django.get_version())
  required += 1


# Test for a json module
try:
  import json
except ImportError:
  try:
    import simplejson
  except ImportError:
    sys.stderr.write("[REQUIRED] Unable to import either the 'json' or 'simplejson' module, at least one is required.\n")
    required += 1


# Test for zope.interface
コード例 #50
0
    def as_string(self):
        """Return a string of the file contents."""
        items = {
            "replaces_str": "",
            "initial_str": "",
        }

        imports = set()

        # Deconstruct operations
        operations = []
        for operation in self.migration.operations:
            operation_string, operation_imports = OperationWriter(
                operation).serialize()
            imports.update(operation_imports)
            operations.append(operation_string)
        items["operations"] = "\n".join(
            operations) + "\n" if operations else ""

        # Format dependencies and write out swappable dependencies right
        dependencies = []
        for dependency in self.migration.dependencies:
            if dependency[0] == "__setting__":
                dependencies.append(
                    "        migrations.swappable_dependency(settings.%s)," %
                    dependency[1])
                imports.add("from django.conf import settings")
            else:
                dependencies.append("        %s," %
                                    self.serialize(dependency)[0])
        items["dependencies"] = "\n".join(
            dependencies) + "\n" if dependencies else ""

        # Format imports nicely, swapping imports of functions from migration files
        # for comments
        migration_imports = set()
        for line in list(imports):
            if re.match(r"^import (.*)\.\d+[^\s]*$", line):
                migration_imports.add(line.split("import")[1].strip())
                imports.remove(line)
                self.needs_manual_porting = True

        # django.db.migrations is always used, but models import may not be.
        # If models import exists, merge it with migrations import.
        if "from django.db import models" in imports:
            imports.discard("from django.db import models")
            imports.add("from django.db import migrations, models")
        else:
            imports.add("from django.db import migrations")

        # Sort imports by the package / module to be imported (the part after
        # "from" in "from ... import ..." or after "import" in "import ...").
        sorted_imports = sorted(imports, key=lambda i: i.split()[1])
        items["imports"] = "\n".join(sorted_imports) + "\n" if imports else ""
        if migration_imports:
            items["imports"] += (
                "\n\n# Functions from the following migrations need manual "
                "copying.\n# Move them and any dependencies into this file, "
                "then update the\n# RunPython operations to refer to the local "
                "versions:\n# %s") % "\n# ".join(sorted(migration_imports))
        # If there's a replaces, make a string for it
        if self.migration.replaces:
            items['replaces_str'] = "\n    replaces = %s\n" % self.serialize(
                self.migration.replaces)[0]
        # Hinting that goes into comment
        if self.include_header:
            items['migration_header'] = MIGRATION_HEADER_TEMPLATE % {
                'version': get_version(),
                'timestamp': now().strftime("%Y-%m-%d %H:%M"),
            }
        else:
            items['migration_header'] = ""

        if self.migration.initial:
            items['initial_str'] = "\n    initial = True\n"

        return MIGRATION_TEMPLATE % items
コード例 #51
0
ファイル: settings.py プロジェクト: uroybd/wagtail-graphql
# django
from django import get_version
from django.conf import settings
# graphql
from graphql import ResolveInfo
from wagtail.core.models import Site

DJANGO_VERSION = get_version()
# settings
if hasattr(settings, 'GRAPHQL_API'):
    SETTINGS = settings.GRAPHQL_API
else:  # pragma: no cover
    SETTINGS = {}
URL_PREFIX = SETTINGS.get('URL_PREFIX', {})
LOAD_GENERIC_SCALARS = SETTINGS.get('GENERIC_SCALARS', True)
RELAY = SETTINGS.get('RELAY', False)

# wagtail settings
try:
    from wagtail.contrib.settings.registry import registry as settings_registry
except ImportError:  # pragma: no cover
    settings_registry = None


def url_prefix_for_site(info: ResolveInfo):
    if DJANGO_VERSION < "2.2":
        hostname = info.context.site.hostname
    else:
        hostname = Site.find_for_request(info.context).hostname
    return URL_PREFIX.get(hostname,
                          info.context.site.root_page.url_path.rstrip('/'))
コード例 #52
0
def get_django_version():
    return django.get_version()
コード例 #53
0
# Django settings for bloodline_server project.

#Project path
import os, sys, random
import django
from django.core.exceptions import SuspiciousOperation

gettext = lambda s: s

PROJECT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
PYTHON_VERSION = '%s.%s' % sys.version_info[:2]
DJANGO_VERSION = django.get_version()

DEBUG = False  # Is in Specific Settings also
TEMPLATE_DEBUG = DEBUG
DAJAXICE_DEBUG = DEBUG

ADMINS = (  # People who receive admin emails
    #    ('Abdeali J Kothari', "*****@*****.**"),
    #    ('Deepak', "*****@*****.**"),
    #    ('Gowtham V', "*****@*****.**"),
)
MANAGERS = ADMINS

# >>>>>>>>>> Moved to SpecificSettings.py
DATABASES = {}
#     'default': {
#         'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
#         'NAME': '',                      # Or path to database file if using sqlite3.
#         'USER': '',                      # Not used with sqlite3.
#         'PASSWORD': '',                  # Not used with sqlite3.
コード例 #54
0
import ssl
import sys

from django.core.servers.basehttp import WSGIRequestHandler
from django.core.servers.basehttp import WSGIServer
from django.core.management.base import CommandError
from django.core.management.commands import runserver
from django.contrib.staticfiles.handlers import StaticFilesHandler
from django import get_version

try:
    from django.core.servers.basehttp import WSGIServerException
except ImportError:
    from socket import error as WSGIServerException

if LooseVersion(get_version()) >= LooseVersion('1.5'):
    from django.utils._os import upath
else:
    upath = unicode


class SecureHTTPServer(WSGIServer):
    def __init__(self, address, handler_cls, certificate, key):
        super(SecureHTTPServer, self).__init__(address, handler_cls)
        self.socket = ssl.wrap_socket(self.socket,
                                      certfile=certificate,
                                      keyfile=key,
                                      server_side=True,
                                      ssl_version=ssl.PROTOCOL_TLSv1,
                                      cert_reqs=ssl.CERT_NONE)
コード例 #55
0
ファイル: models.py プロジェクト: yangshun2005/weixin_market
from __future__ import unicode_literals
from future.utils import with_metaclass

from distutils.version import StrictVersion

from django import get_version, VERSION
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.db.models import Model, Field
from django.db.models.signals import class_prepared
from django.utils import six

from mezzanine.utils.importing import import_dotted_path

# Backward compatibility with Django 1.5's "get_user_model".
if StrictVersion(get_version()) >= StrictVersion('1.5'):
    from django.contrib.auth import get_user_model
else:

    def get_user_model():
        from django.contrib.auth.models import User
        return User


# Emulate Django 1.7's exception-raising get_registered_model
# when running under earlier versions
if VERSION >= (1, 7):
    from django.apps import apps
    get_model = apps.get_registered_model
else:
    from django.db.models import get_model as django_get_model
コード例 #56
0
EMAIL_HOST = 'localhost'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_ENABLED = True
EMAIL_SENDER = '*****@*****.**'
EMAIL_SENDER_DEV = ''
EMAIL_SENDER_PASSWORD_DEV = ''
SENDGRID_API_KEY = os.environ.get('SENDGRID_API_KEY', '')

# Others
GRAPH_MODELS = {
    'all_applications': True,
    'group_models': True,
}

if float(django.get_version()[0:3]) < 1.8:
    FIXTURE_DIRS = (os.path.join(BASE_DIR, 'fixtures'))

# Google Drive
GOOGLE_DRIVE_CLIENT_ID = '960606345011-3bn8sje38i9c0uo8p87ln6tfb2dhco9v.apps.googleusercontent.com'
GOOGLE_DRIVE_CLIENT_SECRET = 'v-gWQKOmuAhTmbJ5REwH-V_1'
GOOGLE_DRIVE_OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'
GOOGLE_DRIVE_REDIRECT_URI = 'http://localhost:8000/api/google-auth-finish'

# Dropbox
DROPBOX_APP_KEY = '__KEY__'
DROPBOX_APP_SECRET = '__SECRET__'
DROPBOX_REDIRECT_URI = 'http://localhost:8000/api/dropbox-auth-finish'

# PayPal
PAYPAL_API_URL = 'https://api.sandbox.paypal.com'
コード例 #57
0
        """
        Process shipping_address trying to get as_text method from address
        and copying.
        You can override this method to process address more granulary
        e.g. you can copy address instance and save FK to it in your order
        class.
        """
        if hasattr(shipping_address, 'as_text'):
            self.shipping_address_text = shipping_address.as_text()
            self.save()


# We need some magic to support django < 1.3 that has no support
# models.on_delete option
f_kwargs = {}
if LooseVersion(django.get_version()) >= LooseVersion('1.3'):
    f_kwargs['on_delete'] = models.SET_NULL


class BaseOrderItem(models.Model):
    """
    A line Item for an order.
    """

    order = models.ForeignKey(get_model_string('Order'),
                              related_name='items',
                              verbose_name=_('Order'))
    product_reference = models.CharField(max_length=255,
                                         verbose_name=_('Product reference'))
    product_name = models.CharField(max_length=255,
                                    null=True,
コード例 #58
0
import textwrap
import readline

import readline
import django
import paramiko
import errno
import pyte
import operator
import getpass
import struct, fcntl, signal, socket, select
from io import open as copen
import uuid

os.environ['DJANGO_SETTINGS_MODULE'] = 'ssh.settings'
if not django.get_version().startswith('1.6'):
    setup = django.setup()

from django.contrib.sessions.models import Session
from django.db.models import Q
from ssh.api import *
from ssh.settings import LOG_DIR, NAV_SORT_BY
from ssh.ansible_api import MyRunner
from ssh.tty_api import Tty
from ssh.models import User, UserPar, Log, AssetGroup

login_user = get_object(UserPar, username=getpass.getuser())

try:
    remote_ip = os.environ.get('SSH_CLIENT').split()[0]
except (IndexError, AttributeError):
コード例 #59
0
ファイル: djangotest.py プロジェクト: waynet/DjangoPi
import django

print 'Using python, print out the django version number to make sure it is installed correctly'
print django.get_version()
コード例 #60
0
ファイル: check.py プロジェクト: OpenCSI/lbe
# -*- coding: utf-8 -*-
print "checking for dependencies ..."
print "............................."
error = False

# Django
print "Django:",
try:
    import django
    if "1.4.6" <= django.get_version():
        print "         \033[92myes\033[0m (" + django.get_version() + ')'
    else:
        error = True
        print "         \033[91mno\033[0m (your version is outdated. Install the latest stable version for LBE)"
except BaseException:
    error = True
    print "         \033[91mno\033[0m (pip install Django)"

# South Migration
print "South migration:",
try:
    import south
    print "\033[92myes\033[0m"
except BaseException:
    error = True
    print "\033[91mno\033[0m (pip install south)"

# Mysql
print "Mysql:",
try:
    import _mysql