Python django.get_version() Examples
The following are 30
code examples of django.get_version().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django
, or try the search function
.
Example #1
Source File: test_writer.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_migration_file_header_comments(self): """ Test comments at top of file. """ migration = type("Migration", (migrations.Migration,), { "operations": [] }) dt = datetime.datetime(2015, 7, 31, 4, 40, 0, 0, tzinfo=utc) with mock.patch('django.db.migrations.writer.now', lambda: dt): for include_header in (True, False): with self.subTest(include_header=include_header): writer = MigrationWriter(migration, include_header) output = writer.as_string() self.assertEqual( include_header, output.startswith( "# Generated by Django %s on 2015-07-31 04:40\n\n" % get_version() ) ) if not include_header: # Make sure the output starts with something that's not # a comment or indentation or blank line self.assertRegex(output.splitlines(keepends=True)[0], r"^[^#\s]+")
Example #2
Source File: __init__.py From Tautulli with GNU General Public License v3.0 | 6 votes |
def import_django_settings(): try: from django.core.exceptions import ImproperlyConfigured try: from django.conf import settings as _django_settings # We can get a situation when Django module is installed in the system, but not initialized, # which means we are running not in a Django process. # In this case the following line throws ImproperlyConfigured exception if 'cloudinary' in _django_settings.INSTALLED_APPS: from django import get_version as _get_django_version global USER_PLATFORM USER_PLATFORM = "Django/{django_version}".format(django_version=_get_django_version()) if 'CLOUDINARY' in dir(_django_settings): return _django_settings.CLOUDINARY else: return None except ImproperlyConfigured: return None except ImportError: return None
Example #3
Source File: test_writer.py From django-sqlserver with MIT License | 6 votes |
def test_migration_file_header_comments(self): """ Test comments at top of file. """ migration = type(str("Migration"), (migrations.Migration,), { "operations": [] }) dt = datetime.datetime(2015, 7, 31, 4, 40, 0, 0, tzinfo=utc) with mock.patch('django.db.migrations.writer.now', lambda: dt): writer = MigrationWriter(migration) output = writer.as_string() self.assertTrue( output.startswith( "# -*- coding: utf-8 -*-\n" "# Generated by Django %(version)s on 2015-07-31 04:40\n" % { 'version': get_version(), } ) )
Example #4
Source File: test_middleware.py From django-cookies-samesite with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_cookie_samesite_django30(self): # Raise DeprecationWarning for newer versions of Django with patch('django.get_version', return_value=DJANGO_SUPPORTED_VERSION): with self.assertRaises(DeprecationWarning) as exc: self.client.get('/cookies-test/') self.assertEqual(exc.exception.args[0], ( 'Your version of Django supports SameSite flag in the cookies mechanism. ' 'You should remove django-cookies-samesite from your project.' )) with patch('django_cookies_samesite.middleware.django.get_version', return_value=DJANGO_SUPPORTED_VERSION): with self.assertRaises(DeprecationWarning) as exc: self.client.get('/cookies-test/') self.assertEqual(exc.exception.args[0], ( 'Your version of Django supports SameSite flag in the cookies mechanism. ' 'You should remove django-cookies-samesite from your project.' ))
Example #5
Source File: registration.py From algoliasearch-django with MIT License | 6 votes |
def __init__(self, settings=SETTINGS): """Initializes the Algolia engine.""" try: app_id = settings['APPLICATION_ID'] api_key = settings['API_KEY'] except KeyError: raise AlgoliaEngineError( 'APPLICATION_ID and API_KEY must be defined.') self.__auto_indexing = settings.get('AUTO_INDEXING', True) self.__settings = settings self.__registered_models = {} self.client = algoliasearch.Client(app_id, api_key) self.client.set_extra_header('User-Agent', 'Algolia for Python (%s); Python (%s); Algolia for Django (%s); Django (%s)' % (CLIENT_VERSION, python_version(), VERSION, django_version))
Example #6
Source File: api.py From yournextrepresentative with GNU Affero General Public License v3.0 | 6 votes |
def get(self, request, *args, **kwargs): result = { 'python_version': sys.version, 'django_version': django.get_version(), 'interesting_user_actions': extra_models.LoggedAction.objects \ .exclude(action_type='set-candidate-not-elected') \ .count(), 'users_who_have_edited': User.objects \ .annotate(edit_count=Count('loggedaction')) \ .filter(edit_count__gt=0).count() } # Try to get the object name of HEAD from git: try: git_version = subprocess.check_output( ['git', 'rev-parse', '--verify', 'HEAD'], cwd=dirname(__file__), universal_newlines=True ).strip() result['git_version'] = git_version except (OSError, subprocess.CalledProcessError): pass return HttpResponse( json.dumps(result), content_type='application/json' )
Example #7
Source File: test_writer.py From djongo with GNU Affero General Public License v3.0 | 6 votes |
def test_migration_file_header_comments(self): """ Test comments at top of file. """ migration = type("Migration", (migrations.Migration,), { "operations": [] }) dt = datetime.datetime(2015, 7, 31, 4, 40, 0, 0, tzinfo=utc) with mock.patch('django.db.migrations.writer.now', lambda: dt): writer = MigrationWriter(migration) output = writer.as_string() self.assertTrue( output.startswith( "# Generated by Django %(version)s on 2015-07-31 04:40\n" % { 'version': get_version(), } ) )
Example #8
Source File: error.py From yats with MIT License | 5 votes |
def process_response(self, request, response): sc = response.status_code if sc in [404]: from django.conf import settings from django.core.mail import mail_admins if not settings.DEBUG: subject = '%d error' % response.status_code try: request_repr = repr(request) except: request_repr = "Request repr() unavailable" try: session_repr = pprint.pformat(request.session._session) except: session_repr = "Session repr() unavailable" from socket import gethostname from yats import get_version, get_python_version from django import get_version as get_django_version yats_data = 'URL: %s\nRAW_POST: %s\nHOST_NAME: %s\nYATS_APP_VERSION: %s\nDJANGO_VERSION: %s\nPYTHON: %s' % (request.build_absolute_uri(), request.body, gethostname(), get_version(), get_django_version(), get_python_version()) if hasattr(request, 'user') and request.user.is_authenticated: yats_data += '\nUSER: %s' % request.user.email message = "%s\n\n%s" % (yats_data, '%s\n\n%s' % (session_repr, request_repr)) mail_admins(subject, message, fail_silently=True) return response
Example #9
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_development(self): ver_tuple = (1, 4, 0, 'alpha', 0) # This will return a different result when it's run within or outside # of a git clone: 1.4.devYYYYMMDDHHMMSS or 1.4. ver_string = get_version(ver_tuple) self.assertRegex(ver_string, r'1\.4(\.dev[0-9]+)?')
Example #10
Source File: views.py From yats with MIT License | 5 votes |
def info(request): from socket import gethostname return render(request, 'info.html', {'hostname': gethostname(), 'version': get_version(), 'date': timezone.now(), 'django': get_django_version(), 'python': get_python_version()})
Example #11
Source File: test_functional.py From drf-schema-adapter with MIT License | 5 votes |
def get_response_data(self, response): import django from distutils.version import LooseVersion self.assertEqual(200, response.status_code) if LooseVersion(django.get_version()) >= LooseVersion('1.9'): return response.json() return response.data
Example #12
Source File: version.py From canvas with BSD 3-Clause "New" or "Revised" License | 5 votes |
def content(self): versions = {} for app in settings.INSTALLED_APPS + ['django']: name = app.split('.')[-1].replace('_', ' ').capitalize() __import__(app) app = sys.modules[app] if hasattr(app, 'get_version'): get_version = app.get_version if callable(get_version): version = get_version() else: version = get_version elif hasattr(app, 'VERSION'): version = app.VERSION elif hasattr(app, '__version__'): version = app.__version__ else: continue if isinstance(version, (list, tuple)): version = '.'.join(str(o) for o in version) versions[name] = version context = self.context.copy() context.update({ 'versions': versions, 'paths': sys.path, }) return render_to_string('debug_toolbar/panels/versions.html', context)
Example #13
Source File: version.py From canvas with BSD 3-Clause "New" or "Revised" License | 5 votes |
def nav_subtitle(self): return 'Django %s' % django.get_version()
Example #14
Source File: simpletags.py From simpleui with MIT License | 5 votes |
def simple_version(): return simpleui.get_version()
Example #15
Source File: apps.py From simpleui with MIT License | 5 votes |
def ready(self): # 如果是django3+ 就使用中间件,删除header中的X-Frame-Options try: import django version = django.get_version() if int(version.split('.')[0]) >= 3: from django.conf import settings mname = 'simpleui.middlewares.SimpleMiddleware' if mname not in settings.MIDDLEWARE: settings.MIDDLEWARE.append(mname) except Exception as e: pass pass
Example #16
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_releases(self): tuples_to_strings = ( ((1, 4, 0, 'alpha', 1), '1.4a1'), ((1, 4, 0, 'beta', 1), '1.4b1'), ((1, 4, 0, 'rc', 1), '1.4rc1'), ((1, 4, 0, 'final', 0), '1.4'), ((1, 4, 1, 'rc', 2), '1.4.1rc2'), ((1, 4, 1, 'final', 0), '1.4.1'), ) for ver_tuple, ver_string in tuples_to_strings: self.assertEqual(get_version(ver_tuple), ver_string)
Example #17
Source File: models.py From django-elasticsearch with MIT License | 5 votes |
def es_syncdb_callback(sender, app=None, created_models=[], **kwargs): if int(get_version()[2]) > 6: models = sender.get_models() else: models = created_models for model in models: if issubclass(model, EsIndexable): model.es.create_index()
Example #18
Source File: test_indexable.py From django-elasticsearch with MIT License | 5 votes |
def setUp(self): from django.db.models.signals import post_save, post_delete try: from django.db.models.signals import post_migrate except ImportError: # django <= 1.6 from django.db.models.signals import post_syncdb as post_migrate from django_elasticsearch.models import es_save_callback from django_elasticsearch.models import es_delete_callback from django_elasticsearch.models import es_syncdb_callback try: from django.apps import apps app = apps.get_app_config('django_elasticsearch') except ImportError: # django 1.4 from django.db.models import get_app app = get_app('django_elasticsearch') post_save.connect(es_save_callback) post_delete.connect(es_delete_callback) post_migrate.connect(es_syncdb_callback) if int(get_version()[2]) >= 6: sender = app else: sender = None post_migrate.send(sender=sender, app_config=app, app=app, # django 1.4 created_models=[TestModel,], verbosity=2) self.instance = TestModel.objects.create(username=u"1", first_name=u"woot", last_name=u"foo") self.instance.es.do_index()
Example #19
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_version(self): "version is handled as a special case" args = ['version'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, get_version())
Example #20
Source File: simpletags.py From simpleui with MIT License | 5 votes |
def load_analysis(context): try: if not get_analysis_config(): return '' # 理论上值一天只上报一次 key = 'simpleui_' + time.strftime('%Y%m%d', time.localtime()) if key in context.request.session: return '' b64 = "" j = { "n": platform.node(), "o": platform.platform(), "p": platform.python_version(), "d": django.get_version(), "s": simpleui.get_version(), } if 'theme_name' in context.request.COOKIES: j['t'] = context.request.COOKIES['theme_name'] else: j['t'] = 'Default' b64 = base64.b64encode(str(j).encode('utf-8')) url = '//simpleui.88cto.com/analysis' b64 = b64.decode('utf-8') html = '<script async type="text/javascript" src="{}/{}"></script>'.format(url, b64); context.request.session[key] = True return mark_safe(html) except: return ''
Example #21
Source File: tests.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_releases(self): tuples_to_strings = ( ((1, 4, 0, 'alpha', 1), '1.4a1'), ((1, 4, 0, 'beta', 1), '1.4b1'), ((1, 4, 0, 'rc', 1), '1.4rc1'), ((1, 4, 0, 'final', 0), '1.4'), ((1, 4, 1, 'rc', 2), '1.4.1rc2'), ((1, 4, 1, 'final', 0), '1.4.1'), ) for ver_tuple, ver_string in tuples_to_strings: self.assertEqual(get_version(ver_tuple), ver_string)
Example #22
Source File: __init__.py From python-compat-runtime with Apache License 2.0 | 5 votes |
def execute(self): """ Given the command-line arguments, this figures out which subcommand is being run, creates a parser appropriate to that command, and runs it. """ # Preprocess options to extract --settings and --pythonpath. # These options could affect the commands that are available, so they # must be processed early. parser = LaxOptionParser(usage="%prog subcommand [options] [args]", version=get_version(), option_list=BaseCommand.option_list) self.autocomplete() try: options, args = parser.parse_args(self.argv) handle_default_options(options) except: pass # Ignore any option errors at this point. try: subcommand = self.argv[1] except IndexError: subcommand = 'help' # Display help if no arguments were given. if subcommand == 'help': if len(args) > 2: self.fetch_command(args[2]).print_help(self.prog_name, args[2]) else: parser.print_lax_help() sys.stderr.write(self.main_help_text() + '\n') sys.exit(1) # Special-cases: We want 'django-admin.py --version' and # 'django-admin.py --help' to work, for backwards compatibility. elif self.argv[1:] == ['--version']: # LaxOptionParser already takes care of printing the version. pass elif self.argv[1:] == ['--help']: parser.print_lax_help() sys.stderr.write(self.main_help_text() + '\n') else: self.fetch_command(subcommand).run_from_argv(self.argv)
Example #23
Source File: views.py From openshift-django17 with MIT License | 5 votes |
def get(self, request, *args, **kwargs): return HttpResponse('Running Django ' + str(get_version()) + " on OpenShift")
Example #24
Source File: __init__.py From django-modern-rpc with MIT License | 5 votes |
def user_is_anonymous(user): if StrictVersion(django.get_version()) < StrictVersion('1.10'): return user.is_anonymous() return user.is_anonymous
Example #25
Source File: __init__.py From django-modern-rpc with MIT License | 5 votes |
def user_is_authenticated(user): if StrictVersion(django.get_version()) < StrictVersion('1.10'): return user.is_authenticated() return user.is_authenticated
Example #26
Source File: test_models.py From cleanerversion with Apache License 2.0 | 5 votes |
def test_create_with_forced_identity(self): # This test does some artificial manipulation of versioned objects, # do not use it as an example # for real-life usage! p = Person.objects.create(name="Abela") # Postgresql will provide protection here, since # util.postgresql.create_current_version_unique_identity_indexes # has been invoked in the post migration handler. if connection.vendor == 'postgresql' and get_version() >= '1.7': with self.assertRaises(IntegrityError): with transaction.atomic(): ident = self.uuid4(p.identity) Person.objects.create(forced_identity=ident, name="Alexis") p.delete() # The start date of p2 does not necessarily have to equal the end date # of p. sleep(0.1) ident = self.uuid4(p.identity) p2 = Person.objects.create(forced_identity=ident, name="Alexis") p2.version_birth_date = p.version_birth_date p2.save() self.assertEqual(p.identity, p2.identity) self.assertNotEqual(p2.id, p2.identity) # Thanks to that artificial manipulation, p is now the previous version # of p2: self.assertEqual(p.name, Person.objects.previous_version(p2).name)
Example #27
Source File: documents_views.py From silver with Apache License 2.0 | 5 votes |
def get_queryset(self): django_version = django.get_version().split('.') if django_version[0] == '1' and int(django_version[1]) < 11: return BillingDocumentBase.objects.filter( Q(kind='invoice') | Q(kind='proforma', related_document=None) ).select_related('customer', 'provider', 'pdf') invoices = BillingDocumentBase.objects \ .filter(kind='invoice') \ .prefetch_related('invoice_transactions__payment_method') proformas = BillingDocumentBase.objects \ .filter(kind='proforma', related_document=None) \ .prefetch_related('proforma_transactions__payment_method') return (invoices | proformas).select_related('customer', 'provider', 'pdf')
Example #28
Source File: base.py From python-compat-runtime with Apache License 2.0 | 5 votes |
def create_parser(self, prog_name, subcommand): """ Create and return the ``OptionParser`` which will be used to parse the arguments to this command. """ return OptionParser(prog=prog_name, usage=self.usage(subcommand), version=self.get_version(), option_list=self.option_list)
Example #29
Source File: base.py From python-compat-runtime with Apache License 2.0 | 5 votes |
def get_version(self): """ Return the Django version, which should be correct for all built-in Django commands. User-supplied commands should override this method. """ return django.get_version()
Example #30
Source File: adapter.py From django-click with MIT License | 5 votes |
def __init__(self, **kwargs): self.kwargs = kwargs self.version = self.kwargs.pop("version", get_version()) context_settings = kwargs.setdefault("context_settings", {}) context_settings["help_option_names"] = ["-h", "--help"]