Here are the examples of the python api django.db.models.DateTimeField taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
65 Examples
5
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_datetime_field(self):
field = models.DateTimeField()
name, path, args, kwargs = field.deconstruct()
self.assertEqual(path, "django.db.models.DateTimeField")
self.assertEqual(args, [])
self.assertEqual(kwargs, {})
field = models.DateTimeField(auto_now_add=True)
name, path, args, kwargs = field.deconstruct()
self.assertEqual(path, "django.db.models.DateTimeField")
self.assertEqual(args, [])
self.assertEqual(kwargs, {"auto_now_add": True})
# Bug #21785
field = models.DateTimeField(auto_now=True, auto_now_add=True)
name, path, args, kwargs = field.deconstruct()
self.assertEqual(path, "django.db.models.DateTimeField")
self.assertEqual(args, [])
self.assertEqual(kwargs, {"auto_now_add": True, "auto_now": True})
def test_decimal_field(self):
3
Source : ranges.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
def process_rhs(self, compiler, connection):
# Transform rhs value for db lookup.
if isinstance(self.rhs, datetime.date):
output_field = models.DateTimeField() if isinstance(self.rhs, datetime.datetime) else models.DateField()
value = models.Value(self.rhs, output_field=output_field)
self.rhs = value.resolve_expression(compiler.query)
return super().process_rhs(compiler, connection)
def as_sql(self, compiler, connection):
3
Source : dates.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
def uses_datetime_field(self):
"""
Return `True` if the date field is a `DateTimeField` and `False`
if it's a `DateField`.
"""
model = self.get_queryset().model if self.model is None else self.model
field = model._meta.get_field(self.get_date_field())
return isinstance(field, models.DateTimeField)
def _make_date_lookup_arg(self, value):
3
Source : ranges.py
with MIT License
from Air-999
with MIT License
from Air-999
def process_rhs(self, compiler, connection):
# Transform rhs value for db lookup.
if isinstance(self.rhs, datetime.date):
output_field = models.DateTimeField() if isinstance(self.rhs, datetime.datetime) else models.DateField()
value = models.Value(self.rhs, output_field=output_field)
self.rhs = value.resolve_expression(compiler.query)
return super().process_rhs(compiler, connection)
def as_postgresql(self, compiler, connection):
3
Source : apps.py
with MIT License
from best-doctor
with MIT License
from best-doctor
def ready(self) -> None:
from django.db import models
from rest_framework.serializers import ModelSerializer
field_mapping = ModelSerializer.serializer_field_mapping
field_mapping[models.DateTimeField] = DateTimeField
for setting in dir(app_settings):
if setting.isupper() and not hasattr(settings, setting):
setattr(settings, setting, getattr(app_settings, setting))
3
Source : decorators.py
with MIT License
from chaitin
with MIT License
from chaitin
def __call__(self, model: Type[models.Model]):
super().__call__(model)
if model._meta.get_field(self.partition_key).get_internal_type() != models.DateTimeField().get_internal_type():
raise ValueError("The partition_key must be DateTimeField type.")
model.partitioning = TimeRangePartitionManager(model, self.partition_key, self.options)
return model
class ListPartitioning(_PartitioningBase):
3
Source : functions.py
with Apache License 2.0
from cockroachdb
with Apache License 2.0
from cockroachdb
def coalesce(self, compiler, connection, **extra_context):
# When coalescing a timestamptz column and a Python datetime, the datetime
# must be cast to timestamptz (DateTimeField) to avoid "incompatible
# COALESCE expressions: expected 'YYYY-MM-DDTHH:MM:SS'::TIMESTAMP to be of
# type timestamptz, found type timestamp".
if self.output_field.get_internal_type() == 'DateTimeField':
clone = self.copy()
clone.set_source_expressions([
Cast(expression, DateTimeField()) for expression in self.get_source_expressions()
])
return super(Coalesce, clone).as_sql(compiler, connection, **extra_context)
return self.as_sql(compiler, connection, **extra_context)
def collate(self, compiler, connection, **extra_context):
3
Source : functions.py
with Apache License 2.0
from cockroachdb
with Apache License 2.0
from cockroachdb
def when(self, compiler, connection, **extra_context):
# As for coalesce(), cast datetimes to timestamptz.
if isinstance(getattr(self.result, 'value', None), datetime.datetime):
self.result = Cast(self.result, DateTimeField())
return self.as_sql(compiler, connection, **extra_context)
def register_functions():
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_mixed_type_annotation_date_interval(self):
active = datetime.datetime(2015, 3, 20, 14, 0, 0)
duration = datetime.timedelta(hours=1)
expires = datetime.datetime(2015, 3, 20, 14, 0, 0) + duration
Ticket.objects.create(active_at=active, duration=duration)
t = Ticket.objects.annotate(
expires=ExpressionWrapper(F('active_at') + F('duration'), output_field=DateTimeField())
).first()
self.assertEqual(t.expires, expires)
def test_mixed_type_annotation_numbers(self):
3
Source : test_datetimefield.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_datetimefield_to_python_microseconds(self):
"""DateTimeField.to_python() supports microseconds."""
f = models.DateTimeField()
self.assertEqual(f.to_python('2001-01-02 03:04:05.000006'), datetime.datetime(2001, 1, 2, 3, 4, 5, 6))
self.assertEqual(f.to_python('2001-01-02 03:04:05.999999'), datetime.datetime(2001, 1, 2, 3, 4, 5, 999999))
def test_timefield_to_python_microseconds(self):
3
Source : clan.py
with MIT License
from gogaz
with MIT License
from gogaz
def clan_weekly_season(request, tag):
try:
clan = Clan.objects.get(tag=tag)
except Clan.DoesNotExist:
return not_found_error("clan", tag)
now = timezone.now()
month = timezone.datetime.strptime("%s-W%s-1 03:00" % (now.year, now.isocalendar()[1]), "%Y-W%W-%w %H:%M")
date = timezone.make_aware(month) - timezone.timedelta(weeks=1)
players = clan.get_players(date).annotate(date=Value(date, output_field=DateTimeField()))
serializer = PlayerWeeklyDonationsSerializer(players, many=True)
return Response(serializer.data)
@api_view(['GET', 'POST'])
3
Source : fix_ambiguous_timestamps.py
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
def handle(self, *app_labels, **options):
self.verbosity = options['verbosity']
self.quiet = self.verbosity < 1
stop = datetime.datetime.now()
start = stop - datetime.timedelta(days=14)
for name, appconf in apps.app_configs.items():
for model in appconf.get_models():
for field in model._meta.fields:
if isinstance(field, models.DateTimeField):
self.fixup(model, field.name, start, stop)
3
Source : validation.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def validate_prepopulated_fields(self, cls, model):
" Validate that prepopulated_fields if a dictionary containing allowed field types. "
# prepopulated_fields
if hasattr(cls, 'prepopulated_fields'):
check_isdict(cls, 'prepopulated_fields', cls.prepopulated_fields)
for field, val in cls.prepopulated_fields.items():
f = get_field(cls, model, 'prepopulated_fields', field)
if isinstance(f, (models.DateTimeField, models.ForeignKey,
models.ManyToManyField)):
raise ImproperlyConfigured("'%s.prepopulated_fields['%s']' "
"is either a DateTimeField, ForeignKey or "
"ManyToManyField. This isn't allowed."
% (cls.__name__, field))
check_isseq(cls, "prepopulated_fields['%s']" % field, val)
for idx, f in enumerate(val):
get_field(cls, model, "prepopulated_fields['%s'][%d]" % (field, idx), f)
def validate_ordering(self, cls, model):
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_datetimefield_to_python_usecs(self):
"""DateTimeField.to_python should support usecs"""
f = models.DateTimeField()
self.assertEqual(f.to_python('2001-01-02 03:04:05.000006'),
datetime.datetime(2001, 1, 2, 3, 4, 5, 6))
self.assertEqual(f.to_python('2001-01-02 03:04:05.999999'),
datetime.datetime(2001, 1, 2, 3, 4, 5, 999999))
def test_timefield_to_python_usecs(self):
3
Source : test_error_messages.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def test_datetime_field_raises_error_message(self):
f = models.DateTimeField()
# Wrong format
self._test_validation_messages(f, 'fõo',
["'fõo' value has an invalid format. It must be "
"in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."])
# Correct format but invalid date
self._test_validation_messages(f, '2011-10-32',
["'2011-10-32' value has the correct format "
"(YYYY-MM-DD) but it is an invalid date."])
# Correct format but invalid date/time
self._test_validation_messages(f, '2011-10-32 10:10',
["'2011-10-32 10:10' value has the correct format "
"(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) "
"but it is an invalid date/time."])
def test_time_field_raises_error_message(self):
3
Source : simpletags.py
with MIT License
from newpanjing
with MIT License
from newpanjing
def get_date_type(spec):
field = spec.field
field_type = ''
if isinstance(field, models.DateTimeField):
field_type = 'datetime'
elif isinstance(field, models.DateField):
field_type = 'date'
elif isinstance(field, models.TimeField):
field_type = 'time'
return field_type
@register.filter
3
Source : widgets.py
with GNU Lesser General Public License v3.0
from opentaps
with GNU Lesser General Public License v3.0
from opentaps
def make_custom_datefields(f, **kwargs):
if isinstance(f, models.DateTimeField):
# return form field with your custom widget here...
return f.formfield(form_class=DateTimeField, **kwargs)
elif isinstance(f, models.DateField):
# return form field with your custom widget here...
return f.formfield(form_class=DateField, **kwargs)
else:
return f.formfield(**kwargs)
3
Source : simple_history.py
with Apache License 2.0
from ShipChain
with Apache License 2.0
from ShipChain
def get_extra_fields(self, model, fields):
extra_fields = super().get_extra_fields(model, fields)
extra_fields['history_date'] = models.DateTimeField(db_index=True)
return extra_fields
class AnonymousHistoricalMixin:
0
Source : filters.py
with GNU General Public License v3.0
from abaoMAO
with GNU General Public License v3.0
from abaoMAO
def __init__(self, field, request, params, model, admin_view, field_path):
self.field_generic = '%s__' % field_path
self.date_params = dict([(FILTER_PREFIX + k, v) for k, v in params.items()
if k.startswith(self.field_generic)])
super(DateFieldListFilter, self).__init__(
field, request, params, model, admin_view, field_path)
now = timezone.now()
# When time zone support is enabled, convert "now" to the user's time
# zone so Django's definition of "Today" matches what the user expects.
if now.tzinfo is not None:
current_tz = timezone.get_current_timezone()
now = now.astimezone(current_tz)
if hasattr(current_tz, 'normalize'):
# available for pytz time zones
now = current_tz.normalize(now)
if isinstance(field, models.DateTimeField):
today = now.replace(hour=0, minute=0, second=0, microsecond=0)
else: # field is a models.DateField
today = now.date()
tomorrow = today + datetime.timedelta(days=1)
self.links = (
(_('Any date'), {}),
(_('Has date'), {
self.lookup_isnull_name: False
}),
(_('Has no date'), {
self.lookup_isnull_name: 'True'
}),
(_('Today'), {
self.lookup_since_name: str(today),
self.lookup_until_name: str(tomorrow),
}),
(_('Past 7 days'), {
self.lookup_since_name: str(today - datetime.timedelta(days=7)),
self.lookup_until_name: str(tomorrow),
}),
(_('This month'), {
self.lookup_since_name: str(today.replace(day=1)),
self.lookup_until_name: str(tomorrow),
}),
(_('This year'), {
self.lookup_since_name: str(today.replace(month=1, day=1)),
self.lookup_until_name: str(tomorrow),
}),
)
def get_context(self):
0
Source : chart.py
with GNU General Public License v3.0
from abaoMAO
with GNU General Public License v3.0
from abaoMAO
def get(self, request, name):
if name not in self.data_charts:
return HttpResponseNotFound()
self.chart = self.data_charts[name]
self.x_field = self.chart['x-field']
y_fields = self.chart['y-field']
self.y_fields = (
y_fields,) if type(y_fields) not in (list, tuple) else y_fields
datas = [{"data":[], "label": force_text(label_for_field(
i, self.model, model_admin=self))} for i in self.y_fields]
self.make_result_list()
for obj in self.result_list:
xf, attrs, value = lookup_field(self.x_field, obj, self)
for i, yfname in enumerate(self.y_fields):
yf, yattrs, yv = lookup_field(yfname, obj, self)
datas[i]["data"].append((value, yv))
option = {'series': {'lines': {'show': True}, 'points': {'show': False}},
'grid': {'hoverable': True, 'clickable': True}}
try:
xfield = self.opts.get_field(self.x_field)
if type(xfield) in (models.DateTimeField, models.DateField, models.TimeField):
option['xaxis'] = {'mode': "time", 'tickLength': 5}
if type(xfield) is models.DateField:
option['xaxis']['timeformat'] = "%y/%m/%d"
elif type(xfield) is models.TimeField:
option['xaxis']['timeformat'] = "%H:%M:%S"
else:
option['xaxis']['timeformat'] = "%y/%m/%d %H:%M:%S"
except Exception:
pass
option.update(self.chart.get('option', {}))
content = {'data': datas, 'option': option}
result = json.dumps(content, cls=JSONEncoder, ensure_ascii=False)
return HttpResponse(result)
site.register_plugin(ChartsPlugin, ListAdminView)
0
Source : checks.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
def _check_prepopulated_fields_key(self, obj, model, field_name, label):
""" Check a key of `prepopulated_fields` dictionary, i.e. check that it
is a name of existing field and the field is one of the allowed types.
"""
try:
field = model._meta.get_field(field_name)
except FieldDoesNotExist:
return refer_to_missing_field(field=field_name, option=label,
model=model, obj=obj, id='admin.E027')
else:
if isinstance(field, (models.DateTimeField, models.ForeignKey, models.ManyToManyField)):
return [
checks.Error(
"The value of '%s' refers to '%s', which must not be a DateTimeField, "
"a ForeignKey, a OneToOneField, or a ManyToManyField." % (label, field_name),
obj=obj.__class__,
id='admin.E028',
)
]
else:
return []
def _check_prepopulated_fields_value(self, obj, model, val, label):
0
Source : filters.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
def __init__(self, field, request, params, model, model_admin, field_path):
self.field_generic = '%s__' % field_path
self.date_params = {k: v for k, v in params.items() if k.startswith(self.field_generic)}
now = timezone.now()
# When time zone support is enabled, convert "now" to the user's time
# zone so Django's definition of "Today" matches what the user expects.
if timezone.is_aware(now):
now = timezone.localtime(now)
if isinstance(field, models.DateTimeField):
today = now.replace(hour=0, minute=0, second=0, microsecond=0)
else: # field is a models.DateField
today = now.date()
tomorrow = today + datetime.timedelta(days=1)
if today.month == 12:
next_month = today.replace(year=today.year + 1, month=1, day=1)
else:
next_month = today.replace(month=today.month + 1, day=1)
next_year = today.replace(year=today.year + 1, month=1, day=1)
self.lookup_kwarg_since = '%s__gte' % field_path
self.lookup_kwarg_until = '%s__lt' % field_path
self.links = (
(_('Any date'), {}),
(_('Today'), {
self.lookup_kwarg_since: str(today),
self.lookup_kwarg_until: str(tomorrow),
}),
(_('Past 7 days'), {
self.lookup_kwarg_since: str(today - datetime.timedelta(days=7)),
self.lookup_kwarg_until: str(tomorrow),
}),
(_('This month'), {
self.lookup_kwarg_since: str(today.replace(day=1)),
self.lookup_kwarg_until: str(next_month),
}),
(_('This year'), {
self.lookup_kwarg_since: str(today.replace(month=1, day=1)),
self.lookup_kwarg_until: str(next_year),
}),
)
if field.null:
self.lookup_kwarg_isnull = '%s__isnull' % field_path
self.links += (
(_('No date'), {self.field_generic + 'isnull': 'True'}),
(_('Has date'), {self.field_generic + 'isnull': 'False'}),
)
super().__init__(field, request, params, model, model_admin, field_path)
def expected_parameters(self):
0
Source : db.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
def get(self, key, default=None, version=None):
key = self.make_key(key, version=version)
self.validate_key(key)
db = router.db_for_read(self.cache_model_class)
connection = connections[db]
table = connection.ops.quote_name(self._table)
with connection.cursor() as cursor:
cursor.execute("SELECT cache_key, value, expires FROM %s "
"WHERE cache_key = %%s" % table, [key])
row = cursor.fetchone()
if row is None:
return default
expires = row[2]
expression = models.Expression(output_field=models.DateTimeField())
for converter in (connection.ops.get_db_converters(expression) +
expression.get_db_converters(connection)):
if func_supports_parameter(converter, 'context'): # RemovedInDjango30Warning
expires = converter(expires, expression, connection, {})
else:
expires = converter(expires, expression, connection)
if expires < timezone.now():
db = router.db_for_write(self.cache_model_class)
connection = connections[db]
with connection.cursor() as cursor:
cursor.execute("DELETE FROM %s "
"WHERE cache_key = %%s" % table, [key])
return default
value = connection.ops.process_clob(row[1])
return pickle.loads(base64.b64decode(force_bytes(value)))
def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
0
Source : db.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
def _base_set(self, mode, key, value, timeout=DEFAULT_TIMEOUT):
timeout = self.get_backend_timeout(timeout)
db = router.db_for_write(self.cache_model_class)
connection = connections[db]
table = connection.ops.quote_name(self._table)
with connection.cursor() as cursor:
cursor.execute("SELECT COUNT(*) FROM %s" % table)
num = cursor.fetchone()[0]
now = timezone.now()
now = now.replace(microsecond=0)
if timeout is None:
exp = datetime.max
elif settings.USE_TZ:
exp = datetime.utcfromtimestamp(timeout)
else:
exp = datetime.fromtimestamp(timeout)
exp = exp.replace(microsecond=0)
if num > self._max_entries:
self._cull(db, cursor, now)
pickled = pickle.dumps(value, pickle.HIGHEST_PROTOCOL)
# The DB column is expecting a string, so make sure the value is a
# string, not bytes. Refs #19274.
b64encoded = base64.b64encode(pickled).decode('latin1')
try:
# Note: typecasting for datetimes is needed by some 3rd party
# database backends. All core backends work without typecasting,
# so be careful about changes here - test suite will NOT pick
# regressions.
with transaction.atomic(using=db):
cursor.execute("SELECT cache_key, expires FROM %s "
"WHERE cache_key = %%s" % table, [key])
result = cursor.fetchone()
if result:
current_expires = result[1]
expression = models.Expression(output_field=models.DateTimeField())
for converter in (connection.ops.get_db_converters(expression) +
expression.get_db_converters(connection)):
if func_supports_parameter(converter, 'context'): # RemovedInDjango30Warning
current_expires = converter(current_expires, expression, connection, {})
else:
current_expires = converter(current_expires, expression, connection)
exp = connection.ops.adapt_datetimefield_value(exp)
if result and (mode == 'set' or (mode == 'add' and current_expires < now)):
cursor.execute("UPDATE %s SET value = %%s, expires = %%s "
"WHERE cache_key = %%s" % table,
[b64encoded, exp, key])
else:
cursor.execute("INSERT INTO %s (cache_key, value, expires) "
"VALUES (%%s, %%s, %%s)" % table,
[key, b64encoded, exp])
except DatabaseError:
# To be threadsafe, updates/inserts are allowed to fail silently
return False
else:
return True
def delete(self, key, version=None):
0
Source : query.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
def datetimes(self, field_name, kind, order='ASC', tzinfo=None):
"""
Return a list of datetime objects representing all available
datetimes for the given field_name, scoped to 'kind'.
"""
assert kind in ("year", "month", "day", "hour", "minute", "second"), \
"'kind' must be one of 'year', 'month', 'day', 'hour', 'minute' or 'second'."
assert order in ('ASC', 'DESC'), \
"'order' must be either 'ASC' or 'DESC'."
if settings.USE_TZ:
if tzinfo is None:
tzinfo = timezone.get_current_timezone()
else:
tzinfo = None
return self.annotate(
datetimefield=Trunc(field_name, kind, output_field=DateTimeField(), tzinfo=tzinfo),
plain_field=F(field_name)
).values_list(
'datetimefield', flat=True
).distinct().filter(plain_field__isnull=False).order_by(('-' if order == 'DESC' else '') + 'datetimefield')
def none(self):
0
Source : checks.py
with MIT License
from Air-999
with MIT License
from Air-999
def _check_prepopulated_fields_key(self, obj, field_name, label):
""" Check a key of `prepopulated_fields` dictionary, i.e. check that it
is a name of existing field and the field is one of the allowed types.
"""
try:
field = obj.model._meta.get_field(field_name)
except FieldDoesNotExist:
return refer_to_missing_field(field=field_name, option=label, obj=obj, id='admin.E027')
else:
if isinstance(field, (models.DateTimeField, models.ForeignKey, models.ManyToManyField)):
return [
checks.Error(
"The value of '%s' refers to '%s', which must not be a DateTimeField, "
"a ForeignKey, a OneToOneField, or a ManyToManyField." % (label, field_name),
obj=obj.__class__,
id='admin.E028',
)
]
else:
return []
def _check_prepopulated_fields_value(self, obj, val, label):
0
Source : admin_list.py
with MIT License
from Air-999
with MIT License
from Air-999
def date_hierarchy(cl):
"""
Display the date hierarchy for date drill-down functionality.
"""
if cl.date_hierarchy:
field_name = cl.date_hierarchy
field = get_fields_from_path(cl.model, field_name)[-1]
if isinstance(field, models.DateTimeField):
dates_or_datetimes = 'datetimes'
qs_kwargs = {'is_dst': True}
else:
dates_or_datetimes = 'dates'
qs_kwargs = {}
year_field = '%s__year' % field_name
month_field = '%s__month' % field_name
day_field = '%s__day' % field_name
field_generic = '%s__' % field_name
year_lookup = cl.params.get(year_field)
month_lookup = cl.params.get(month_field)
day_lookup = cl.params.get(day_field)
def link(filters):
return cl.get_query_string(filters, [field_generic])
if not (year_lookup or month_lookup or day_lookup):
# select appropriate start level
date_range = cl.queryset.aggregate(first=models.Min(field_name),
last=models.Max(field_name))
if date_range['first'] and date_range['last']:
if dates_or_datetimes == 'datetimes':
date_range = {
k: timezone.localtime(v) if timezone.is_aware(v) else v
for k, v in date_range.items()
}
if date_range['first'].year == date_range['last'].year:
year_lookup = date_range['first'].year
if date_range['first'].month == date_range['last'].month:
month_lookup = date_range['first'].month
if year_lookup and month_lookup and day_lookup:
day = datetime.date(int(year_lookup), int(month_lookup), int(day_lookup))
return {
'show': True,
'back': {
'link': link({year_field: year_lookup, month_field: month_lookup}),
'title': capfirst(formats.date_format(day, 'YEAR_MONTH_FORMAT'))
},
'choices': [{'title': capfirst(formats.date_format(day, 'MONTH_DAY_FORMAT'))}]
}
elif year_lookup and month_lookup:
days = getattr(cl.queryset, dates_or_datetimes)(field_name, 'day', **qs_kwargs)
return {
'show': True,
'back': {
'link': link({year_field: year_lookup}),
'title': str(year_lookup)
},
'choices': [{
'link': link({year_field: year_lookup, month_field: month_lookup, day_field: day.day}),
'title': capfirst(formats.date_format(day, 'MONTH_DAY_FORMAT'))
} for day in days]
}
elif year_lookup:
months = getattr(cl.queryset, dates_or_datetimes)(field_name, 'month', **qs_kwargs)
return {
'show': True,
'back': {
'link': link({}),
'title': _('All dates')
},
'choices': [{
'link': link({year_field: year_lookup, month_field: month.month}),
'title': capfirst(formats.date_format(month, 'YEAR_MONTH_FORMAT'))
} for month in months]
}
else:
years = getattr(cl.queryset, dates_or_datetimes)(field_name, 'year', **qs_kwargs)
return {
'show': True,
'back': None,
'choices': [{
'link': link({year_field: str(year.year)}),
'title': str(year.year),
} for year in years]
}
@register.tag(name='date_hierarchy')
0
Source : db.py
with MIT License
from Air-999
with MIT License
from Air-999
def get_many(self, keys, version=None):
if not keys:
return {}
key_map = {}
for key in keys:
self.validate_key(key)
key_map[self.make_key(key, version)] = key
db = router.db_for_read(self.cache_model_class)
connection = connections[db]
quote_name = connection.ops.quote_name
table = quote_name(self._table)
with connection.cursor() as cursor:
cursor.execute(
'SELECT %s, %s, %s FROM %s WHERE %s IN (%s)' % (
quote_name('cache_key'),
quote_name('value'),
quote_name('expires'),
table,
quote_name('cache_key'),
', '.join(['%s'] * len(key_map)),
),
list(key_map),
)
rows = cursor.fetchall()
result = {}
expired_keys = []
expression = models.Expression(output_field=models.DateTimeField())
converters = (connection.ops.get_db_converters(expression) + expression.get_db_converters(connection))
for key, value, expires in rows:
for converter in converters:
expires = converter(expires, expression, connection)
if expires < timezone.now():
expired_keys.append(key)
else:
value = connection.ops.process_clob(value)
value = pickle.loads(base64.b64decode(value.encode()))
result[key_map.get(key)] = value
self._base_delete_many(expired_keys)
return result
def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
0
Source : db.py
with MIT License
from Air-999
with MIT License
from Air-999
def _base_set(self, mode, key, value, timeout=DEFAULT_TIMEOUT):
timeout = self.get_backend_timeout(timeout)
db = router.db_for_write(self.cache_model_class)
connection = connections[db]
quote_name = connection.ops.quote_name
table = quote_name(self._table)
with connection.cursor() as cursor:
cursor.execute("SELECT COUNT(*) FROM %s" % table)
num = cursor.fetchone()[0]
now = timezone.now()
now = now.replace(microsecond=0)
if timeout is None:
exp = datetime.max
elif settings.USE_TZ:
exp = datetime.utcfromtimestamp(timeout)
else:
exp = datetime.fromtimestamp(timeout)
exp = exp.replace(microsecond=0)
if num > self._max_entries:
self._cull(db, cursor, now)
pickled = pickle.dumps(value, self.pickle_protocol)
# The DB column is expecting a string, so make sure the value is a
# string, not bytes. Refs #19274.
b64encoded = base64.b64encode(pickled).decode('latin1')
try:
# Note: typecasting for datetimes is needed by some 3rd party
# database backends. All core backends work without typecasting,
# so be careful about changes here - test suite will NOT pick
# regressions.
with transaction.atomic(using=db):
cursor.execute(
'SELECT %s, %s FROM %s WHERE %s = %%s' % (
quote_name('cache_key'),
quote_name('expires'),
table,
quote_name('cache_key'),
),
[key]
)
result = cursor.fetchone()
if result:
current_expires = result[1]
expression = models.Expression(output_field=models.DateTimeField())
for converter in (connection.ops.get_db_converters(expression) +
expression.get_db_converters(connection)):
current_expires = converter(current_expires, expression, connection)
exp = connection.ops.adapt_datetimefield_value(exp)
if result and mode == 'touch':
cursor.execute(
'UPDATE %s SET %s = %%s WHERE %s = %%s' % (
table,
quote_name('expires'),
quote_name('cache_key')
),
[exp, key]
)
elif result and (mode == 'set' or (mode == 'add' and current_expires < now)):
cursor.execute(
'UPDATE %s SET %s = %%s, %s = %%s WHERE %s = %%s' % (
table,
quote_name('value'),
quote_name('expires'),
quote_name('cache_key'),
),
[b64encoded, exp, key]
)
elif mode != 'touch':
cursor.execute(
'INSERT INTO %s (%s, %s, %s) VALUES (%%s, %%s, %%s)' % (
table,
quote_name('cache_key'),
quote_name('value'),
quote_name('expires'),
),
[key, b64encoded, exp]
)
else:
return False # touch failed.
except DatabaseError:
# To be threadsafe, updates/inserts are allowed to fail silently
return False
else:
return True
def delete(self, key, version=None):
0
Source : query.py
with MIT License
from Air-999
with MIT License
from Air-999
def datetimes(self, field_name, kind, order='ASC', tzinfo=None, is_dst=None):
"""
Return a list of datetime objects representing all available
datetimes for the given field_name, scoped to 'kind'.
"""
assert kind in ('year', 'month', 'week', 'day', 'hour', 'minute', 'second'), \
"'kind' must be one of 'year', 'month', 'week', 'day', 'hour', 'minute', or 'second'."
assert order in ('ASC', 'DESC'), \
"'order' must be either 'ASC' or 'DESC'."
if settings.USE_TZ:
if tzinfo is None:
tzinfo = timezone.get_current_timezone()
else:
tzinfo = None
return self.annotate(
datetimefield=Trunc(
field_name,
kind,
output_field=DateTimeField(),
tzinfo=tzinfo,
is_dst=is_dst,
),
plain_field=F(field_name)
).values_list(
'datetimefield', flat=True
).distinct().filter(plain_field__isnull=False).order_by(('-' if order == 'DESC' else '') + 'datetimefield')
def none(self):
0
Source : managers.py
with Mozilla Public License 2.0
from Amsterdam
with Mozilla Public License 2.0
from Amsterdam
def retrieve_valid_sessions(self):
"""
Returns a queryset containing Sessions that fit one of the following conditions:
* The submit_before is set and is still valid
* The submit_before is NOT set, the Session is in use and the started_at + duration is still valid
* The submit_before is NOT set and the Session is NOT in use
And all of these conditions must only contain Sessions that are not frozen. Frozen sessions cannot be edited!
"""
queryset = self.get_queryset()
return queryset.annotate(
# Calculate the submit before based on the started_at + duration
submit_before_based_on_duration=ExpressionWrapper(
F('started_at') + F('duration'),
output_field=DateTimeField()
)
).filter(
(
# All sessions that have a submit_before that has not yet passed
(Q(submit_before__isnull=False) & Q(submit_before__gt=Now())) |
# All sessions that do not have a submit_before but where the created_at + duration has not yet passed
(Q(submit_before__isnull=True) & Q(submit_before_based_on_duration__gt=Now())) |
# All sessions that have no submit_before and has not yet been answered
(Q(submit_before__isnull=True) & Q(submit_before_based_on_duration__isnull=True))
),
# Frozen session are not editable anymore
frozen=False,
).all()
0
Source : filters.py
with MIT License
from andreynovikov
with MIT License
from andreynovikov
def __init__(self, field, request, params, model, model_admin, field_path):
self.field_name = field_path
self.lookup_kwarg_gte = '{}__gte'.format(field_path)
self.lookup_kwarg_lte = '{}__lte'.format(field_path)
self.lookup_gte = params.get(self.lookup_kwarg_gte)
self.lookup_lte = params.get(self.lookup_kwarg_lte)
# todo: check if this is required in default admin
if self.lookup_gte == '':
params.pop(self.lookup_kwarg_gte)
if self.lookup_lte == '':
params.pop(self.lookup_kwarg_lte)
if self.lookup_gte and self.lookup_lte:
self.lookup_val = '{} - {}'.format(self.lookup_gte, self.lookup_lte)
# if we are filtering DateTimeField we should add one day to final date
if "__" in field_path:
related_model, field = field_path.split("__")
field = model._meta.get_field(related_model).related_model._meta.get_field(field)
else:
field = model._meta.get_field(field_path)
if isinstance(field, models.DateTimeField):
try:
gte_date = datetime.datetime.strptime(self.lookup_gte, '%Y-%m-%d')
lte_date = datetime.datetime.strptime(self.lookup_lte, '%Y-%m-%d')
lte_date = lte_date + datetime.timedelta(seconds=3600*24-1)
if settings.USE_TZ:
gte_date = timezone.make_aware(gte_date, timezone.get_current_timezone())
lte_date = timezone.make_aware(lte_date, timezone.get_current_timezone())
params[self.lookup_kwarg_gte] = gte_date.strftime('%Y-%m-%d %H:%M:%S%z')
params[self.lookup_kwarg_lte] = lte_date.strftime('%Y-%m-%d %H:%M:%S%z')
except ValueError:
messages.add_message(request, messages.ERROR, _("Invalid date for '%(field_name)s' field range filter") % {'field_name': field.verbose_name})
else:
self.lookup_val = ''
super(DateRangeFilter, self).__init__(field, request, params, model, model_admin, field_path)
def get_template(self):
0
Source : filters.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def __init__(self, field, request, params, model, model_admin, field_path):
self.field_generic = '%s__' % field_path
self.date_params = {k: v for k, v in params.items() if k.startswith(self.field_generic)}
now = timezone.now()
# When time zone support is enabled, convert "now" to the user's time
# zone so Django's definition of "Today" matches what the user expects.
if timezone.is_aware(now):
now = timezone.localtime(now)
if isinstance(field, models.DateTimeField):
today = now.replace(hour=0, minute=0, second=0, microsecond=0)
else: # field is a models.DateField
today = now.date()
tomorrow = today + datetime.timedelta(days=1)
if today.month == 12:
next_month = today.replace(year=today.year + 1, month=1, day=1)
else:
next_month = today.replace(month=today.month + 1, day=1)
next_year = today.replace(year=today.year + 1, month=1, day=1)
self.lookup_kwarg_since = '%s__gte' % field_path
self.lookup_kwarg_until = '%s__lt' % field_path
self.links = (
(_('Any date'), {}),
(_('Today'), {
self.lookup_kwarg_since: str(today),
self.lookup_kwarg_until: str(tomorrow),
}),
(_('Past 7 days'), {
self.lookup_kwarg_since: str(today - datetime.timedelta(days=7)),
self.lookup_kwarg_until: str(tomorrow),
}),
(_('This month'), {
self.lookup_kwarg_since: str(today.replace(day=1)),
self.lookup_kwarg_until: str(next_month),
}),
(_('This year'), {
self.lookup_kwarg_since: str(today.replace(month=1, day=1)),
self.lookup_kwarg_until: str(next_year),
}),
)
if field.null:
self.lookup_kwarg_isnull = '%s__isnull' % field_path
self.links += (
(_('No date'), {self.field_generic + 'isnull': 'True'}),
(_('Has date'), {self.field_generic + 'isnull': 'False'}),
)
super(DateFieldListFilter, self).__init__(
field, request, params, model, model_admin, field_path)
def expected_parameters(self):
0
Source : admin_list.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def date_hierarchy(cl):
"""
Displays the date hierarchy for date drill-down functionality.
"""
if cl.date_hierarchy:
field_name = cl.date_hierarchy
field = get_fields_from_path(cl.model, field_name)[-1]
dates_or_datetimes = 'datetimes' if isinstance(field, models.DateTimeField) else 'dates'
year_field = '%s__year' % field_name
month_field = '%s__month' % field_name
day_field = '%s__day' % field_name
field_generic = '%s__' % field_name
year_lookup = cl.params.get(year_field)
month_lookup = cl.params.get(month_field)
day_lookup = cl.params.get(day_field)
def link(filters):
return cl.get_query_string(filters, [field_generic])
if not (year_lookup or month_lookup or day_lookup):
# select appropriate start level
date_range = cl.queryset.aggregate(first=models.Min(field_name),
last=models.Max(field_name))
if date_range['first'] and date_range['last']:
if date_range['first'].year == date_range['last'].year:
year_lookup = date_range['first'].year
if date_range['first'].month == date_range['last'].month:
month_lookup = date_range['first'].month
if year_lookup and month_lookup and day_lookup:
day = datetime.date(int(year_lookup), int(month_lookup), int(day_lookup))
return {
'show': True,
'back': {
'link': link({year_field: year_lookup, month_field: month_lookup}),
'title': capfirst(formats.date_format(day, 'YEAR_MONTH_FORMAT'))
},
'choices': [{'title': capfirst(formats.date_format(day, 'MONTH_DAY_FORMAT'))}]
}
elif year_lookup and month_lookup:
days = cl.queryset.filter(**{year_field: year_lookup, month_field: month_lookup})
days = getattr(days, dates_or_datetimes)(field_name, 'day')
return {
'show': True,
'back': {
'link': link({year_field: year_lookup}),
'title': str(year_lookup)
},
'choices': [{
'link': link({year_field: year_lookup, month_field: month_lookup, day_field: day.day}),
'title': capfirst(formats.date_format(day, 'MONTH_DAY_FORMAT'))
} for day in days]
}
elif year_lookup:
months = cl.queryset.filter(**{year_field: year_lookup})
months = getattr(months, dates_or_datetimes)(field_name, 'month')
return {
'show': True,
'back': {
'link': link({}),
'title': _('All dates')
},
'choices': [{
'link': link({year_field: year_lookup, month_field: month.month}),
'title': capfirst(formats.date_format(month, 'YEAR_MONTH_FORMAT'))
} for month in months]
}
else:
years = getattr(cl.queryset, dates_or_datetimes)(field_name, 'year')
return {
'show': True,
'choices': [{
'link': link({year_field: str(year.year)}),
'title': str(year.year),
} for year in years]
}
@register.inclusion_tag('admin/search_form.html')
0
Source : functions.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def __init__(self, output_field=None, **extra):
if output_field is None:
output_field = DateTimeField()
super(TransactionNow, self).__init__(output_field=output_field, **extra)
0
Source : db.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def get(self, key, default=None, version=None):
key = self.make_key(key, version=version)
self.validate_key(key)
db = router.db_for_read(self.cache_model_class)
connection = connections[db]
table = connection.ops.quote_name(self._table)
with connection.cursor() as cursor:
cursor.execute("SELECT cache_key, value, expires FROM %s "
"WHERE cache_key = %%s" % table, [key])
row = cursor.fetchone()
if row is None:
return default
expires = row[2]
expression = models.Expression(output_field=models.DateTimeField())
for converter in (connection.ops.get_db_converters(expression) +
expression.get_db_converters(connection)):
expires = converter(expires, expression, connection, {})
if expires < timezone.now():
db = router.db_for_write(self.cache_model_class)
connection = connections[db]
with connection.cursor() as cursor:
cursor.execute("DELETE FROM %s "
"WHERE cache_key = %%s" % table, [key])
return default
value = connection.ops.process_clob(row[1])
return pickle.loads(base64.b64decode(force_bytes(value)))
def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
0
Source : db.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def _base_set(self, mode, key, value, timeout=DEFAULT_TIMEOUT):
timeout = self.get_backend_timeout(timeout)
db = router.db_for_write(self.cache_model_class)
connection = connections[db]
table = connection.ops.quote_name(self._table)
with connection.cursor() as cursor:
cursor.execute("SELECT COUNT(*) FROM %s" % table)
num = cursor.fetchone()[0]
now = timezone.now()
now = now.replace(microsecond=0)
if timeout is None:
exp = datetime.max
elif settings.USE_TZ:
exp = datetime.utcfromtimestamp(timeout)
else:
exp = datetime.fromtimestamp(timeout)
exp = exp.replace(microsecond=0)
if num > self._max_entries:
self._cull(db, cursor, now)
pickled = pickle.dumps(value, pickle.HIGHEST_PROTOCOL)
b64encoded = base64.b64encode(pickled)
# The DB column is expecting a string, so make sure the value is a
# string, not bytes. Refs #19274.
if six.PY3:
b64encoded = b64encoded.decode('latin1')
try:
# Note: typecasting for datetimes is needed by some 3rd party
# database backends. All core backends work without typecasting,
# so be careful about changes here - test suite will NOT pick
# regressions.
with transaction.atomic(using=db):
cursor.execute("SELECT cache_key, expires FROM %s "
"WHERE cache_key = %%s" % table, [key])
result = cursor.fetchone()
if result:
current_expires = result[1]
expression = models.Expression(output_field=models.DateTimeField())
for converter in (connection.ops.get_db_converters(expression) +
expression.get_db_converters(connection)):
current_expires = converter(current_expires, expression, connection, {})
exp = connection.ops.adapt_datetimefield_value(exp)
if result and (mode == 'set' or (mode == 'add' and current_expires < now)):
cursor.execute("UPDATE %s SET value = %%s, expires = %%s "
"WHERE cache_key = %%s" % table,
[b64encoded, exp, key])
else:
cursor.execute("INSERT INTO %s (cache_key, value, expires) "
"VALUES (%%s, %%s, %%s)" % table,
[key, b64encoded, exp])
except DatabaseError:
# To be threadsafe, updates/inserts are allowed to fail silently
return False
else:
return True
def delete(self, key, version=None):
0
Source : query.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def datetimes(self, field_name, kind, order='ASC', tzinfo=None):
"""
Returns a list of datetime objects representing all available
datetimes for the given field_name, scoped to 'kind'.
"""
assert kind in ("year", "month", "day", "hour", "minute", "second"), \
"'kind' must be one of 'year', 'month', 'day', 'hour', 'minute' or 'second'."
assert order in ('ASC', 'DESC'), \
"'order' must be either 'ASC' or 'DESC'."
if settings.USE_TZ:
if tzinfo is None:
tzinfo = timezone.get_current_timezone()
else:
tzinfo = None
return self.annotate(
datetimefield=Trunc(field_name, kind, output_field=DateTimeField(), tzinfo=tzinfo),
plain_field=F(field_name)
).values_list(
'datetimefield', flat=True
).distinct().filter(plain_field__isnull=False).order_by(('-' if order == 'DESC' else '') + 'datetimefield')
def none(self):
0
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def output_field(self):
return models.DateTimeField()
def as_sql(self, compiler, connection):
0
Source : test_datetime.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_trunc_func(self):
start_datetime = microsecond_support(datetime(2015, 6, 15, 14, 30, 50, 321))
end_datetime = microsecond_support(datetime(2016, 6, 15, 14, 10, 50, 123))
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime, is_dst=False)
end_datetime = timezone.make_aware(end_datetime, is_dst=False)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
msg = 'output_field must be either DateField, TimeField, or DateTimeField'
with self.assertRaisesMessage(ValueError, msg):
list(DTModel.objects.annotate(truncated=Trunc('start_datetime', 'year', output_field=IntegerField())))
with self.assertRaisesMessage(AssertionError, "'name' isn't a DateField, TimeField, or DateTimeField."):
list(DTModel.objects.annotate(truncated=Trunc('name', 'year', output_field=DateTimeField())))
with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'start_date' to DateTimeField"):
list(DTModel.objects.annotate(truncated=Trunc('start_date', 'second')))
with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"):
list(DTModel.objects.annotate(truncated=Trunc('start_time', 'month')))
with self.assertRaisesMessage(ValueError, "Cannot truncate DateField 'start_date' to DateTimeField"):
list(DTModel.objects.annotate(truncated=Trunc('start_date', 'month', output_field=DateTimeField())))
with self.assertRaisesMessage(ValueError, "Cannot truncate TimeField 'start_time' to DateTimeField"):
list(DTModel.objects.annotate(truncated=Trunc('start_time', 'second', output_field=DateTimeField())))
def test_datetime_kind(kind):
self.assertQuerysetEqual(
DTModel.objects.annotate(
truncated=Trunc('start_datetime', kind, output_field=DateTimeField())
).order_by('start_datetime'),
[
(start_datetime, truncate_to(start_datetime, kind)),
(end_datetime, truncate_to(end_datetime, kind))
],
lambda m: (m.start_datetime, m.truncated)
)
def test_date_kind(kind):
self.assertQuerysetEqual(
DTModel.objects.annotate(
truncated=Trunc('start_date', kind, output_field=DateField())
).order_by('start_datetime'),
[
(start_datetime, truncate_to(start_datetime.date(), kind)),
(end_datetime, truncate_to(end_datetime.date(), kind))
],
lambda m: (m.start_datetime, m.truncated)
)
def test_time_kind(kind):
self.assertQuerysetEqual(
DTModel.objects.annotate(
truncated=Trunc('start_time', kind, output_field=TimeField())
).order_by('start_datetime'),
[
(start_datetime, truncate_to(start_datetime.time(), kind)),
(end_datetime, truncate_to(end_datetime.time(), kind))
],
lambda m: (m.start_datetime, m.truncated)
)
test_date_kind('year')
test_date_kind('month')
test_date_kind('day')
test_time_kind('hour')
test_time_kind('minute')
test_time_kind('second')
test_datetime_kind('year')
test_datetime_kind('month')
test_datetime_kind('day')
test_datetime_kind('hour')
test_datetime_kind('minute')
test_datetime_kind('second')
qs = DTModel.objects.filter(start_datetime__date=Trunc('start_datetime', 'day', output_field=DateField()))
self.assertEqual(qs.count(), 2)
def test_trunc_year_func(self):
0
Source : test_datetime.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_trunc_func_with_timezone(self):
"""
If the truncated datetime transitions to a different offset (daylight
saving) then the returned value will have that new timezone/offset.
"""
start_datetime = microsecond_support(datetime(2015, 6, 15, 14, 30, 50, 321))
end_datetime = microsecond_support(datetime(2016, 6, 15, 14, 10, 50, 123))
start_datetime = timezone.make_aware(start_datetime, is_dst=False)
end_datetime = timezone.make_aware(end_datetime, is_dst=False)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
melb = pytz.timezone('Australia/Melbourne')
def test_datetime_kind(kind):
self.assertQuerysetEqual(
DTModel.objects.annotate(
truncated=Trunc('start_datetime', kind, output_field=DateTimeField(), tzinfo=melb)
).order_by('start_datetime'),
[
(start_datetime, truncate_to(start_datetime.astimezone(melb), kind, melb)),
(end_datetime, truncate_to(end_datetime.astimezone(melb), kind, melb))
],
lambda m: (m.start_datetime, m.truncated)
)
def test_date_kind(kind):
self.assertQuerysetEqual(
DTModel.objects.annotate(
truncated=Trunc('start_date', kind, output_field=DateField(), tzinfo=melb)
).order_by('start_datetime'),
[
(start_datetime, truncate_to(start_datetime.date(), kind)),
(end_datetime, truncate_to(end_datetime.date(), kind))
],
lambda m: (m.start_datetime, m.truncated)
)
def test_time_kind(kind):
self.assertQuerysetEqual(
DTModel.objects.annotate(
truncated=Trunc('start_time', kind, output_field=TimeField(), tzinfo=melb)
).order_by('start_datetime'),
[
(start_datetime, truncate_to(start_datetime.time(), kind)),
(end_datetime, truncate_to(end_datetime.time(), kind))
],
lambda m: (m.start_datetime, m.truncated)
)
test_date_kind('year')
test_date_kind('month')
test_date_kind('day')
test_time_kind('hour')
test_time_kind('minute')
test_time_kind('second')
test_datetime_kind('year')
test_datetime_kind('month')
test_datetime_kind('day')
test_datetime_kind('hour')
test_datetime_kind('minute')
test_datetime_kind('second')
qs = DTModel.objects.filter(start_datetime__date=Trunc('start_datetime', 'day', output_field=DateField()))
self.assertEqual(qs.count(), 2)
0
Source : test_writer.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_simple_migration(self):
"""
Tests serializing a simple migration.
"""
fields = {
'charfield': models.DateTimeField(default=datetime.datetime.utcnow),
'datetimefield': models.DateTimeField(default=datetime.datetime.utcnow),
}
options = {
'verbose_name': 'My model',
'verbose_name_plural': 'My models',
}
migration = type(str("Migration"), (migrations.Migration,), {
"operations": [
migrations.CreateModel("MyModel", tuple(fields.items()), options, (models.Model,)),
migrations.CreateModel("MyModel2", tuple(fields.items()), bases=(models.Model,)),
migrations.CreateModel(
name="MyModel3", fields=tuple(fields.items()), options=options, bases=(models.Model,)
),
migrations.DeleteModel("MyModel"),
migrations.AddField("OtherModel", "datetimefield", fields["datetimefield"]),
],
"dependencies": [("testapp", "some_other_one")],
})
writer = MigrationWriter(migration)
output = writer.as_string()
# We don't test the output formatting - that's too fragile.
# Just make sure it runs for now, and that things look alright.
result = self.safe_exec(output)
self.assertIn("Migration", result)
# In order to preserve compatibility with Python 3.2 unicode literals
# prefix shouldn't be added to strings.
tokens = tokenize.generate_tokens(six.StringIO(str(output)).readline)
for token_type, token_source, (srow, scol), __, line in tokens:
if token_type == tokenize.STRING:
self.assertFalse(
token_source.startswith('u'),
"Unicode literal prefix found at %d:%d: %r" % (
srow, scol, line.strip()
)
)
# Silence warning on Python 2: Not importing directory
# 'tests/migrations/migrations_test_apps/without_init_file/migrations':
# missing __init__.py
@ignore_warnings(category=ImportWarning)
0
Source : test_writer.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_sorted_imports(self):
"""
#24155 - Tests ordering of imports.
"""
migration = type(str("Migration"), (migrations.Migration,), {
"operations": [
migrations.AddField("mymodel", "myfield", models.DateTimeField(
default=datetime.datetime(2012, 1, 1, 1, 1, tzinfo=utc),
)),
]
})
writer = MigrationWriter(migration)
output = writer.as_string()
self.assertIn(
"import datetime\n"
"from django.db import migrations, models\n"
"from django.utils.timezone import utc\n",
output
)
def test_migration_file_header_comments(self):
0
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_orders_nulls_first_on_filtered_subquery(self):
Article.objects.filter(headline='Article 1').update(author=self.author_1)
Article.objects.filter(headline='Article 2').update(author=self.author_1)
Article.objects.filter(headline='Article 4').update(author=self.author_2)
Author.objects.filter(name__isnull=True).delete()
author_3 = Author.objects.create(name='Name 3')
article_subquery = Article.objects.filter(
author=OuterRef('pk'),
headline__icontains='Article',
).order_by().values('author').annotate(
last_date=Max('pub_date'),
).values('last_date')
self.assertQuerysetEqualReversible(
Author.objects.annotate(
last_date=Subquery(article_subquery, output_field=DateTimeField())
).order_by(
F('last_date').asc(nulls_first=True)
).distinct(),
[author_3, self.author_1, self.author_2],
)
def test_stop_slicing(self):
0
Source : test_error_messages.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_datetime_field_raises_error_message(self):
f = models.DateTimeField()
# Wrong format
self._test_validation_messages(
f, 'fõo',
["'fõo' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]
)
# Correct format but invalid date
self._test_validation_messages(
f, '2011-10-32',
["'2011-10-32' value has the correct format (YYYY-MM-DD) but it is an invalid date."]
)
# Correct format but invalid date/time
self._test_validation_messages(
f, '2011-10-32 10:10',
["'2011-10-32 10:10' value has the correct format (YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) "
"but it is an invalid date/time."]
)
def test_time_field_raises_error_message(self):
0
Source : tasks.py
with BSD 2-Clause "Simplified" License
from getmetamapper
with BSD 2-Clause "Simplified" License
from getmetamapper
def queue_domain_verifications(self, *arg, **kwargs):
"""Scheduled task to queue domains that need to be verified.
"""
next_attempt_at = ExpressionWrapper(
RawSQL("last_attempted_at + INTERVAL '1 hour' * POW(attempts, 1.5)", []),
output_field=DateTimeField()
)
sso_domains = SSODomain.objects.annotate(next_attempt_at=next_attempt_at)
sso_domains = sso_domains.filter(attempts__lte=SSODomain.MAX_ATTEMPTS)
sso_domains = sso_domains.filter(
Q(next_attempt_at__gte=Now()) | Q(last_attempted_at__isnull=True)
)
self.log.info(
'Found {0} domains'.format(len(sso_domains))
)
for sso_domain in sso_domains:
self.log.info(
'Queueing {0} for verification'.format(sso_domain)
)
verify_domain.apply_async(args=(sso_domain.domain,))
@app.task(bind=True)
0
Source : db.py
with Apache License 2.0
from i13-msrg
with Apache License 2.0
from i13-msrg
def get(self, key, default=None, version=None):
key = self.make_key(key, version=version)
self.validate_key(key)
db = router.db_for_read(self.cache_model_class)
connection = connections[db]
quote_name = connection.ops.quote_name
table = quote_name(self._table)
with connection.cursor() as cursor:
cursor.execute(
'SELECT %s, %s, %s FROM %s WHERE %s = %%s' % (
quote_name('cache_key'),
quote_name('value'),
quote_name('expires'),
table,
quote_name('cache_key'),
),
[key]
)
row = cursor.fetchone()
if row is None:
return default
expires = row[2]
expression = models.Expression(output_field=models.DateTimeField())
for converter in (connection.ops.get_db_converters(expression) +
expression.get_db_converters(connection)):
if func_supports_parameter(converter, 'context'): # RemovedInDjango30Warning
expires = converter(expires, expression, connection, {})
else:
expires = converter(expires, expression, connection)
if expires < timezone.now():
db = router.db_for_write(self.cache_model_class)
connection = connections[db]
with connection.cursor() as cursor:
cursor.execute(
'DELETE FROM %s WHERE %s = %%s' % (
table,
quote_name('cache_key'),
),
[key]
)
return default
value = connection.ops.process_clob(row[1])
return pickle.loads(base64.b64decode(value.encode()))
def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
0
Source : db.py
with Apache License 2.0
from i13-msrg
with Apache License 2.0
from i13-msrg
def _base_set(self, mode, key, value, timeout=DEFAULT_TIMEOUT):
timeout = self.get_backend_timeout(timeout)
db = router.db_for_write(self.cache_model_class)
connection = connections[db]
quote_name = connection.ops.quote_name
table = quote_name(self._table)
with connection.cursor() as cursor:
cursor.execute("SELECT COUNT(*) FROM %s" % table)
num = cursor.fetchone()[0]
now = timezone.now()
now = now.replace(microsecond=0)
if timeout is None:
exp = datetime.max
elif settings.USE_TZ:
exp = datetime.utcfromtimestamp(timeout)
else:
exp = datetime.fromtimestamp(timeout)
exp = exp.replace(microsecond=0)
if num > self._max_entries:
self._cull(db, cursor, now)
pickled = pickle.dumps(value, pickle.HIGHEST_PROTOCOL)
# The DB column is expecting a string, so make sure the value is a
# string, not bytes. Refs #19274.
b64encoded = base64.b64encode(pickled).decode('latin1')
try:
# Note: typecasting for datetimes is needed by some 3rd party
# database backends. All core backends work without typecasting,
# so be careful about changes here - test suite will NOT pick
# regressions.
with transaction.atomic(using=db):
cursor.execute(
'SELECT %s, %s FROM %s WHERE %s = %%s' % (
quote_name('cache_key'),
quote_name('expires'),
table,
quote_name('cache_key'),
),
[key]
)
result = cursor.fetchone()
if result:
current_expires = result[1]
expression = models.Expression(output_field=models.DateTimeField())
for converter in (connection.ops.get_db_converters(expression) +
expression.get_db_converters(connection)):
if func_supports_parameter(converter, 'context'): # RemovedInDjango30Warning
current_expires = converter(current_expires, expression, connection, {})
else:
current_expires = converter(current_expires, expression, connection)
exp = connection.ops.adapt_datetimefield_value(exp)
if result and mode == 'touch':
cursor.execute(
'UPDATE %s SET %s = %%s WHERE %s = %%s' % (
table,
quote_name('expires'),
quote_name('cache_key')
),
[exp, key]
)
elif result and (mode == 'set' or (mode == 'add' and current_expires < now)):
cursor.execute(
'UPDATE %s SET %s = %%s, %s = %%s WHERE %s = %%s' % (
table,
quote_name('value'),
quote_name('expires'),
quote_name('cache_key'),
),
[b64encoded, exp, key]
)
elif mode != 'touch':
cursor.execute(
'INSERT INTO %s (%s, %s, %s) VALUES (%%s, %%s, %%s)' % (
table,
quote_name('cache_key'),
quote_name('value'),
quote_name('expires'),
),
[key, b64encoded, exp]
)
else:
return False # touch failed.
except DatabaseError:
# To be threadsafe, updates/inserts are allowed to fail silently
return False
else:
return True
def delete(self, key, version=None):
0
Source : query.py
with Apache License 2.0
from i13-msrg
with Apache License 2.0
from i13-msrg
def datetimes(self, field_name, kind, order='ASC', tzinfo=None):
"""
Return a list of datetime objects representing all available
datetimes for the given field_name, scoped to 'kind'.
"""
assert kind in ('year', 'month', 'week', 'day', 'hour', 'minute', 'second'), \
"'kind' must be one of 'year', 'month', 'week', 'day', 'hour', 'minute', or 'second'."
assert order in ('ASC', 'DESC'), \
"'order' must be either 'ASC' or 'DESC'."
if settings.USE_TZ:
if tzinfo is None:
tzinfo = timezone.get_current_timezone()
else:
tzinfo = None
return self.annotate(
datetimefield=Trunc(field_name, kind, output_field=DateTimeField(), tzinfo=tzinfo),
plain_field=F(field_name)
).values_list(
'datetimefield', flat=True
).distinct().filter(plain_field__isnull=False).order_by(('-' if order == 'DESC' else '') + 'datetimefield')
def none(self):
0
Source : user.py
with GNU Lesser General Public License v3.0
from indietyp
with GNU Lesser General Public License v3.0
from indietyp
def punishment(request, u=None, validated={}, *args, **kwargs):
try:
user = User.objects.get(id=u)
except Exception as e:
return 'non existent user queried - {}'.format(e), 403
Punishment.objects\
.annotate(completion=ExpressionWrapper(F('created_at') + F('length'),
output_field=DateTimeField()))\
.filter(completion__lte=timezone.now(),
resolved=False,
length__isnull=False).update(resolved=True)
if request.method == 'GET':
punishments = Punishment.objects.filter(user=user)
if validated['server'] is not None:
server = Server.objects.get(id=validated['server'])
punishments = punishments.filter(Q(server=server) | Q(server=None))
if validated['resolved'] is not None:
punishments = punishments.filter(resolved=validated['resolved'])
if validated['muted'] is not None:
punishments = punishments.filter(is_muted=validated['muted'])
if validated['banned'] is not None:
punishments = punishments.filter(is_banned=validated['banned'])
if validated['gagged'] is not None:
punishments = punishments.filter(is_gagged=validated['gagged'])
if validated['kicked'] is not None:
punishments = punishments.filter(is_kicked=validated['kicked'])
return [p for p in punishments.annotate(admin=F('created_by__namespace'))
.values('id',
'user',
'server',
'created_at',
'reason',
'resolved',
'created_by',
'length',
'is_banned',
'is_kicked',
'is_muted',
'is_gagged',
'admin')], 200
elif request.method == 'PUT':
if 'server' in validated:
server = Server.objects.get(id=validated['server'])
else:
server = None
if validated['length'] > 0:
length = datetime.timedelta(seconds=validated['length'])
else:
length = None
punishment = Punishment(user=user,
server=server,
reason=validated['reason'],
is_muted=validated['muted'],
is_gagged=validated['gagged'],
is_kicked=validated['kicked'],
is_banned=validated['banned'],
length=length,
created_by=request.user)
punishment.save()
if validated['plugin']:
server = [server] if server else Server.objects.all()
for s in server:
if punishment.is_gagged or punishment.is_muted:
SourcemodPluginWrapper(s).mutegag(punishment)
if punishment.is_banned:
SourcemodPluginWrapper(s).ban(punishment)
if punishment.is_kicked:
punishment.resolved = True
punishment.save()
SourcemodPluginWrapper(s).kick(punishment)
@csrf_exempt
See More Examples