def get_version(version=None):
"Returns a PEP 440-compliant version number from VERSION."
version = get_complete_version(version)
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha releases
# | {a|b|rc}N - for alpha, beta, and rc releases
main = get_main_version(version)
sub = ''
if version[3] == 'alpha' and version[4] == 0:
git_changeset = get_git_changeset()
if git_changeset:
sub = '.dev%s' % git_changeset
elif version[3] != 'final':
mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'rc'}
sub = mapping[version[3]] + str(version[4])
return str(main + sub)
python类VERSION的实例源码
def get_git_changeset():
"""Returns a numeric identifier of the latest git changeset.
The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format.
This value isn't guaranteed to be unique, but collisions are very unlikely,
so it's sufficient for generating the development version numbers.
"""
repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
git_log = subprocess.Popen(
'git log --pretty=format:%ct --quiet -1 HEAD',
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
shell=True, cwd=repo_dir, universal_newlines=True,
)
timestamp = git_log.communicate()[0]
try:
timestamp = datetime.datetime.utcfromtimestamp(int(timestamp))
except ValueError:
return None
return timestamp.strftime('%Y%m%d%H%M%S')
def registration_status_view(self, request):
request.current_app = self.admin_site.name
version = "{}.{}.{}".format(VERSION[0], VERSION[1], VERSION[2])
insecure = self.is_insecure(version)
data = {
"django_version": version,
"insecure": insecure,
}
template = "".join(render_to_string("insecure.html", data).splitlines())
data["template"] = template
data["run_again_at"] = time.time() + 60 * 60 * 24
request.session["pyup_django"] = data
return HttpResponse(json.dumps(data), content_type="application/json")
def run_tests(base_dir=None, apps=None, verbosity=1, interavtive=False):
base_dir = base_dir or os.path.dirname(__file__)
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
sys.path.insert(0, os.path.join(base_dir, 'src'))
sys.path.insert(0, os.path.join(base_dir, 'tests'))
import django
if django.VERSION >= (1,7):
django.setup()
from django.conf import settings
from django.test.utils import get_runner
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=verbosity,
interavtive=interavtive,
failfast=False)
if apps:
app_tests = [x.strip() for x in apps if x]
else:
app_tests = [
'notification'
]
failures = test_runner.run_tests(app_tests)
sys.exit(bool(failures))
widgets.py 文件源码
项目:django-autocomplete-light-selectize
作者: litchfield
项目源码
文件源码
阅读 28
收藏 0
点赞 0
评论 0
def render_options(self, *args):
"""
Variation to DAL default, which adds selected_choices to choices
"""
selected_choices_arg = 1 if VERSION < (1, 10) else 0
# Filter out None values, not needed for autocomplete
selected_choices = [c for c in args[selected_choices_arg] if c]
if self.url:
all_choices = copy.copy(self.choices)
self.choices += [ (c, c) for c in selected_choices ]
self.filter_choices_to_render(selected_choices)
html = super(WidgetMixin, self).render_options(*args)
if self.url:
self.choices = all_choices
return html
def get_version(version=None):
"Returns a PEP 440-compliant version number from VERSION."
version = get_complete_version(version)
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha releases
# | {a|b|rc}N - for alpha, beta, and rc releases
main = get_main_version(version)
sub = ''
if version[3] == 'alpha' and version[4] == 0:
git_changeset = get_git_changeset()
if git_changeset:
sub = '.dev%s' % git_changeset
elif version[3] != 'final':
mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'rc'}
sub = mapping[version[3]] + str(version[4])
return str(main + sub)
def get_git_changeset():
"""Returns a numeric identifier of the latest git changeset.
The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format.
This value isn't guaranteed to be unique, but collisions are very unlikely,
so it's sufficient for generating the development version numbers.
"""
repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
git_log = subprocess.Popen(
'git log --pretty=format:%ct --quiet -1 HEAD',
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
shell=True, cwd=repo_dir, universal_newlines=True,
)
timestamp = git_log.communicate()[0]
try:
timestamp = datetime.datetime.utcfromtimestamp(int(timestamp))
except ValueError:
return None
return timestamp.strftime('%Y%m%d%H%M%S')
def render(self, name, value, attrs=None):
if value is None:
value = ""
if VERSION < (1, 11):
final_attrs = self.build_attrs(attrs, name=name)
else:
final_attrs = self.build_attrs(attrs, {'name': name})
final_attrs = self.build_attrs(final_attrs, self.attrs)
if "class" not in final_attrs:
final_attrs["class"] = ""
final_attrs["class"] += " wmd-input"
template = loader.get_template(self.template)
# Compatibility fix:
# see https://github.com/timmyomahony/django-pagedown/issues/42
context = {
"attrs": flatatt(final_attrs),
"body": conditional_escape(force_unicode(value)),
"id": final_attrs["id"],
"show_preview": self.show_preview,
}
context = Context(context) if VERSION < (1, 9) else context
return template.render(context)
def test_form_edit(self):
if VERSION <= (1, 9):
url = '/admin/auth/group/1/'
else:
url = '/admin/auth/group/1/change/'
# GET the import form
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
data = {
'name': 'admins',
'permissions': ('1', '2'),
'users': ('1',),
}
response = self.client.post(url, data, follow=True)
self.assertEqual(response.status_code, 200)
group = Group.objects.all().last()
self.assertTrue(group.name == 'admins')
self.assertTrue(group.permissions.all().count() == 2)
self.assertTrue(group.user_set.first() == self.admin)
def get_next_url(request, redirect_field_name):
"""Retrieves next url from request
Note: This verifies that the url is safe before returning it. If the url
is not safe, this returns None.
:arg HttpRequest request: the http request
:arg str redirect_field_name: the name of the field holding the next url
:returns: safe url or None
"""
next_url = request.GET.get(redirect_field_name)
if next_url:
kwargs = {
'url': next_url,
'host': request.get_host()
}
# NOTE(willkg): Django 1.11+ allows us to require https, too.
if django.VERSION >= (1, 11):
kwargs['require_https'] = request.is_secure()
is_safe = is_safe_url(**kwargs)
if is_safe:
return next_url
return None
def test_https(self):
# If the request is for HTTPS and the next url is HTTPS, then that
# works with all Djangos.
req = self.factory.get(
'/',
data={'next': 'https://testserver/foo'},
secure=True,
)
self.assertEquals(req.is_secure(), True)
next_url = views.get_next_url(req, 'next')
self.assertEqual(next_url, 'https://testserver/foo')
# For Django 1.11+, if the request is for HTTPS and the next url is
# HTTP, then that fails.
if django.VERSION >= (1, 11):
req = self.factory.get(
'/',
data={'next': 'http://testserver/foo'},
secure=True,
)
self.assertEquals(req.is_secure(), True)
next_url = views.get_next_url(req, 'next')
self.assertEqual(next_url, None)
def get_version(version=None):
"Returns a PEP 386-compliant version number from VERSION."
version = get_complete_version(version)
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha releases
# | {a|b|c}N - for alpha, beta and rc releases
main = get_main_version(version)
sub = ''
if version[3] == 'alpha' and version[4] == 0:
git_changeset = get_git_changeset()
if git_changeset:
sub = '.dev%s' % git_changeset
elif version[3] != 'final':
mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
sub = mapping[version[3]] + str(version[4])
return str(main + sub)
def get_git_changeset():
"""Returns a numeric identifier of the latest git changeset.
The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format.
This value isn't guaranteed to be unique, but collisions are very unlikely,
so it's sufficient for generating the development version numbers.
"""
repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
git_log = subprocess.Popen('git log --pretty=format:%ct --quiet -1 HEAD',
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
shell=True, cwd=repo_dir, universal_newlines=True)
timestamp = git_log.communicate()[0]
try:
timestamp = datetime.datetime.utcfromtimestamp(int(timestamp))
except ValueError:
return None
return timestamp.strftime('%Y%m%d%H%M%S')
def full_clean(self, *args, **kwargs):
# autogenerate slugs for non-empty title translation
for lang_code in mt_settings.AVAILABLE_LANGUAGES:
title_field = build_localized_fieldname('title', lang_code)
slug_field = build_localized_fieldname('slug', lang_code)
title = getattr(self, title_field)
slug = getattr(self, slug_field)
if title and not slug:
if DJANGO_VERSION >= (1, 9):
base_slug = slugify(title, allow_unicode=True)
else:
base_slug = slugify(title)
if base_slug:
setattr(self, slug_field, self._get_autogenerated_lang_slug(base_slug, lang_code))
super(Page, self).full_clean(*args, **kwargs)
def DjangoVersion():
"""Discover the version of Django installed.
Returns:
A distutils.version.LooseVersion.
"""
try:
__import__('django.' + _DESIRED_DJANGO_VERSION)
except ImportError:
pass
import django
try:
return distutils.version.LooseVersion('.'.join(map(str, django.VERSION)))
except AttributeError:
return LooseVersion(django.VERSION)
def content(self, value):
workbook = None
if not bool(value) or not len(value): # Short-circuit to protect against empty querysets/empty lists/None, etc
self._container = []
return
elif isinstance(value, list):
workbook = self._serialize_list(value)
elif isinstance(value, QuerySet):
workbook = self._serialize_queryset(value)
if django.VERSION < (1, 9):
if isinstance(value, ValuesQuerySet):
workbook = self._serialize_values_queryset(value)
if workbook is None:
raise ValueError('ExcelResponse accepts the following data types: list, dict, QuerySet, ValuesQuerySet')
if self.force_csv:
self['Content-Type'] = 'text/csv; charset=utf8'
self['Content-Disposition'] = 'attachment;filename={}.csv'.format(self.output_filename)
workbook.seek(0)
workbook = self.make_bytes(workbook.getvalue())
else:
self['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
self['Content-Disposition'] = 'attachment; filename={}.xlsx'.format(self.output_filename)
workbook = save_virtual_workbook(workbook)
self._container = [self.make_bytes(workbook)]
def __init__(self, nodelist, limit_name, **limit_kwargs):
extra_kwargs = {}
if django.VERSION[:2] > (1, 8):
extra_kwargs['func'] = None
super(DjptLimitNode, self).__init__(
takes_context=False, args=[limit_name], kwargs=limit_kwargs,
**extra_kwargs
)
self.nodelist = nodelist
def force_no_ordering(self):
"""
"ORDER BY NULL" prevents MySQL from implicitly ordering by grouped
columns. If no ordering would otherwise be applied, we don't want any
implicit sorting going on.
"""
if django.VERSION >= (1, 8):
return [(None, ("NULL", [], False))]
else:
return ["NULL"]
def get_context_data(self, **kwargs):
context = super(AboutView, self).get_context_data(**kwargs)
# django
context['DJANGO_VERSION'] = '{}.{}.{}'.format(
django.VERSION[0], # major
django.VERSION[1], # minor
django.VERSION[2], # micro
)
# python
context['PYTHON_VERSION'] = '{}.{}.{}'.format(
sys.version_info.major,
sys.version_info.minor,
sys.version_info.micro,
)
# Salesforce DX
out = subprocess.check_output(['sfdx', '--version'])
match = re.match(r'sfdx-cli/(\d+.\d+.\d+)-.+', out)
if match:
context['SFDX_CLI_VERSION'] = match.group(1)
# cumulusci
context['CUMULUSCI_VERSION'] = get_installed_version('cumulusci')
# heroku
heroku_env_vars = [
'HEROKU_APP_ID',
'HEROKU_APP_NAME',
'HEROKU_DYNO_ID',
'HEROKU_RELEASE_CREATED_AT',
'HEROKU_RELEASE_VERSION',
'HEROKU_SLUG_COMMIT',
'HEROKU_SLUG_DESCRIPTION',
]
for var in heroku_env_vars:
context[var] = os.environ.get(var,
'Heroku dyno metadata not found')
return context