def _get_response(self):
timestamp = date_format(self.object.created_on, 'DATETIME_FORMAT')
data = {
'text': self.object.text,
'signature': "{} | {}".format(self.object.sent_by.username,
timestamp),
}
return {'status': True, 'data': data}
python类date_format()的实例源码
def date(value, arg=None):
"""Formats a date according to the given format."""
if value in (None, ''):
return ''
if arg is None:
arg = settings.DATE_FORMAT
try:
return formats.date_format(value, arg)
except AttributeError:
try:
return format(value, arg)
except AttributeError:
return ''
def create():
""" Creates a backup of the database. Optionally gzipped. """
# Backup file with day name included, for weekly rotation.
backup_file = os.path.join(get_backup_directory(), 'dsmrreader-{}-backup-{}.sql'.format(
connection.vendor, formats.date_format(timezone.now().date(), 'l')
))
# PostgreSQL backup.
if connection.vendor == 'postgresql': # pragma: no cover
backup_process = subprocess.Popen(
[
settings.DSMRREADER_BACKUP_PG_DUMP,
'--host={}'.format(settings.DATABASES['default']['HOST']),
'--user={}'.format(settings.DATABASES['default']['USER']),
settings.DATABASES['default']['NAME'],
], env={
'PGPASSWORD': settings.DATABASES['default']['PASSWORD']
},
stdout=open(backup_file, 'w') # pragma: no cover
)
# MySQL backup.
elif connection.vendor == 'mysql': # pragma: no cover
backup_process = subprocess.Popen(
[
settings.DSMRREADER_BACKUP_MYSQLDUMP,
'--compress',
'--hex-blob',
'--extended-insert',
'--quick',
'--host', settings.DATABASES['default']['HOST'],
'--user', settings.DATABASES['default']['USER'],
'--password={}'.format(settings.DATABASES['default']['PASSWORD']),
settings.DATABASES['default']['NAME'],
],
stdout=open(backup_file, 'w') # pragma: no cover
)
# SQLite backup.
elif connection.vendor == 'sqlite': # pragma: no cover
backup_process = subprocess.Popen(
[
settings.DSMRREADER_BACKUP_SQLITE,
settings.DATABASES['default']['NAME'],
'.dump',
],
stdout=open(backup_file, 'w')
) # pragma: no cover
else:
raise NotImplementedError('Unsupported backup backend: {}'.format(connection.vendor)) # pragma: no cover
backup_process.wait()
backup_settings = BackupSettings.get_solo()
if backup_settings.compress:
compress(file_path=backup_file)
backup_settings.latest_backup = timezone.now()
backup_settings.save()
def test_archive(self, now_mock):
now_mock.return_value = timezone.make_aware(timezone.datetime(2016, 1, 1))
response = self.client.get(
reverse('{}:archive'.format(self.namespace))
)
self.assertEqual(response.status_code, 200)
self.assertIn('capabilities', response.context)
# XHR's.
data = {
'date': formats.date_format(timezone.now().date(), 'DSMR_DATEPICKER_DATE_FORMAT'),
}
if self.support_data:
self.assertEqual(response.context['start_date'], date(2016, 1, 1))
self.assertEqual(response.context['end_date'], date(2016, 1, 2))
for current_level in ('days', 'months', 'years'):
# Test both with tariffs sparated and merged.
for merge in (False, True):
frontend_settings = FrontendSettings.get_solo()
frontend_settings.merge_electricity_tariffs = merge
frontend_settings.save()
data.update({'level': current_level})
response = self.client.get(
reverse('{}:archive-xhr-summary'.format(self.namespace)), data=data
)
self.assertEqual(response.status_code, 200)
response = self.client.get(
reverse('{}:archive-xhr-graphs'.format(self.namespace)), data=data
)
self.assertEqual(response.status_code, 200, response.content)
# Invalid XHR.
data.update({'level': 'INVALID DATA'})
response = self.client.get(
reverse('{}:archive-xhr-summary'.format(self.namespace)), data=data
)
self.assertEqual(response.status_code, 500)
response = self.client.get(
reverse('{}:archive-xhr-graphs'.format(self.namespace)), data=data
)
self.assertEqual(response.status_code, 500)
def test_show_add_cases_to_run(self):
self.login_tester()
url = reverse('add-cases-to-run', args=[self.test_run.pk])
response = self.client.get(url)
self.assertNotContains(
response,
'<a href="{0}">{1}</a>'.format(
reverse('testcases-get',
args=[self.proposed_case.pk]),
self.proposed_case.pk),
html=True
)
confirmed_cases = [self.case, self.case_1, self.case_2, self.case_3]
# Check selected and unselected case id checkboxes
# cls.case is not added to cls.test_run, so it should not be checked.
self.assertContains(
response,
'<td align="left">'
'<input type="checkbox" name="case" value="{0}">'
'</td>'.format(self.case.pk),
html=True)
# other cases are added to cls.test_run, so must be checked.
for case in confirmed_cases[1:]:
self.assertContains(
response,
'<td align="left">'
'<input type="checkbox" name="case" value="{0}" '
'disabled="true" checked="true">'
'</td>'.format(case.pk),
html=True)
# Check listed case properties
# note: the response is ordered by 'case'
for loop_counter, case in enumerate(confirmed_cases, 1):
html_pieces = [
'<a href="{0}">{1}</a>'.format(
reverse('testcases-get', args=[case.pk]),
case.pk),
'<td class="js-case-summary" data-param="{0}">'
'<a id="link_{0}" class="blind_title_link" '
'href="javascript:void(0);">{1}</a></td>'.format(loop_counter,
case.summary),
'<td>{0}</td>'.format(case.author.username),
'<td>{0}</td>'.format(
formats.date_format(case.create_date, 'DATETIME_FORMAT')),
'<td>{0}</td>'.format(case.category.name),
'<td>{0}</td>'.format(case.priority.value),
]
for html in html_pieces:
self.assertContains(response, html, html=True)
def form_valid(self, form):
message = form.cleaned_data.get('comment')
image = form.cleaned_data.get("image")
users = (self.request.POST.get('users[]','')).split(",")
user = self.request.user
subject = self.pdf_file.topic.subject
if (users[0] is not ''):
for u in users:
to_user = User.objects.get(email=u)
talk, create = Conversation.objects.get_or_create(user_one=user,user_two=to_user)
created = TalkMessages.objects.create(text=message,talk=talk,user=user,subject=subject,image=image)
simple_notify = textwrap.shorten(strip_tags(message), width = 30, placeholder = "...")
if image is not '':
simple_notify += " ".join(_("[Photo]"))
notification = {
"type": "chat",
"subtype": "subject",
"space": subject.slug,
"user_icon": created.user.image_url,
"notify_title": str(created.user),
"simple_notify": simple_notify,
"view_url": reverse("chat:view_message", args = (created.id, ), kwargs = {}),
"complete": render_to_string("chat/_message.html", {"talk_msg": created}, self.request),
"container": "chat-" + str(created.user.id),
"last_date": _("Last message in %s")%(formats.date_format(created.create_date, "SHORT_DATETIME_FORMAT"))
}
notification = json.dumps(notification)
Group("user-%s" % to_user.id).send({'text': notification})
ChatVisualizations.objects.create(viewed = False, message = created, user = to_user)
success = str(_('The message was successfull sent!'))
return JsonResponse({"message":success})
erro = HttpResponse(str(_("No user selected!")))
erro.status_code = 404
return erro
def form_valid(self, form):
message = form.cleaned_data.get('comment')
image = form.cleaned_data.get("image")
users = (self.request.POST.get('users[]','')).split(",")
user = self.request.user
subject = self.link.topic.subject
if (users[0] is not ''):
for u in users:
to_user = User.objects.get(email=u)
talk, create = Conversation.objects.get_or_create(user_one=user,user_two=to_user)
created = TalkMessages.objects.create(text=message,talk=talk,user=user,subject=subject,image=image)
simple_notify = textwrap.shorten(strip_tags(message), width = 30, placeholder = "...")
if image is not '':
simple_notify += " ".join(_("[Photo]"))
notification = {
"type": "chat",
"subtype": "subject",
"space": subject.slug,
"user_icon": created.user.image_url,
"notify_title": str(created.user),
"simple_notify": simple_notify,
"view_url": reverse("chat:view_message", args = (created.id, ), kwargs = {}),
"complete": render_to_string("chat/_message.html", {"talk_msg": created}, self.request),
"container": "chat-" + str(created.user.id),
"last_date": _("Last message in %s")%(formats.date_format(created.create_date, "SHORT_DATETIME_FORMAT"))
}
notification = json.dumps(notification)
Group("user-%s" % to_user.id).send({'text': notification})
ChatVisualizations.objects.create(viewed = False, message = created, user = to_user)
success = str(_('The message was successfull sent!'))
return JsonResponse({"message":success})
erro = HttpResponse(str(_("No user selected!")))
erro.status_code = 404
return erro
def form_valid(self, form):
message = form.cleaned_data.get('comment')
image = form.cleaned_data.get("image")
users = (self.request.POST.get('users[]','')).split(",")
user = self.request.user
subject = self.webconference.topic.subject
if (users[0] is not ''):
for u in users:
to_user = User.objects.get(email=u)
talk, create = Conversation.objects.get_or_create(user_one=user,user_two=to_user)
created = TalkMessages.objects.create(text=message,talk=talk,user=user,subject=subject,image=image)
simple_notify = textwrap.shorten(strip_tags(message), width = 30, placeholder = "...")
if image is not '':
simple_notify += " ".join(_("[Photo]"))
notification = {
"type": "chat",
"subtype": "subject",
"space": subject.slug,
"user_icon": created.user.image_url,
"notify_title": str(created.user),
"simple_notify": simple_notify,
"view_url": reverse("chat:view_message", args = (created.id, ), kwargs = {}),
"complete": render_to_string("chat/_message.html", {"talk_msg": created}, self.request),
"container": "chat-" + str(created.user.id),
"last_date": _("Last message in %s")%(formats.date_format(created.create_date, "SHORT_DATETIME_FORMAT"))
}
notification = json.dumps(notification)
Group("user-%s" % to_user.id).send({'text': notification})
ChatVisualizations.objects.create(viewed = False, message = created, user = to_user)
success = str(_('The message was successfull sent!'))
return JsonResponse({"message":success})
erro = HttpResponse(str(_("No user selected!")))
erro.status_code = 404
return erro
def form_valid(self, form):
message = form.cleaned_data.get('comment')
image = form.cleaned_data.get("image")
users = (self.request.POST.get('users[]','')).split(",")
user = self.request.user
subject = self.bulletin.topic.subject
if (users[0] is not ''):
for u in users:
to_user = User.objects.get(email=u)
talk, create = Conversation.objects.get_or_create(user_one=user,user_two=to_user)
created = TalkMessages.objects.create(text=message,talk=talk,user=user,subject=subject,image=image)
simple_notify = textwrap.shorten(strip_tags(message), width = 30, placeholder = "...")
if image is not '':
simple_notify += " ".join(_("[Photo]"))
notification = {
"type": "chat",
"subtype": "subject",
"space": subject.slug,
"user_icon": created.user.image_url,
"notify_title": str(created.user),
"simple_notify": simple_notify,
"view_url": reverse("chat:view_message", args = (created.id, ), kwargs = {}),
"complete": render_to_string("chat/_message.html", {"talk_msg": created}, self.request),
"container": "chat-" + str(created.user.id),
"last_date": _("Last message in %s")%(formats.date_format(created.create_date, "SHORT_DATETIME_FORMAT"))
}
notification = json.dumps(notification)
Group("user-%s" % to_user.id).send({'text': notification})
ChatVisualizations.objects.create(viewed = False, message = created, user = to_user)
success = str(_('The message was successfull sent!'))
return JsonResponse({"message":success})
erro = HttpResponse(str(_("No user selected!")))
erro.status_code = 404
return erro
def form_valid(self, form):
message = form.cleaned_data.get('comment')
image = form.cleaned_data.get("image")
users = (self.request.POST.get('users[]','')).split(",")
user = self.request.user
subject = self.webpage.topic.subject
if (users[0] is not ''):
for u in users:
to_user = User.objects.get(email=u)
talk, create = Conversation.objects.get_or_create(user_one=user,user_two=to_user)
created = TalkMessages.objects.create(text=message,talk=talk,user=user,subject=subject,image=image)
simple_notify = textwrap.shorten(strip_tags(message), width = 30, placeholder = "...")
if image is not '':
simple_notify += " ".join(_("[Photo]"))
notification = {
"type": "chat",
"subtype": "subject",
"space": subject.slug,
"user_icon": created.user.image_url,
"notify_title": str(created.user),
"simple_notify": simple_notify,
"view_url": reverse("chat:view_message", args = (created.id, ), kwargs = {}),
"complete": render_to_string("chat/_message.html", {"talk_msg": created}, self.request),
"container": "chat-" + str(created.user.id),
"last_date": _("Last message in %s")%(formats.date_format(created.create_date, "SHORT_DATETIME_FORMAT"))
}
notification = json.dumps(notification)
Group("user-%s" % to_user.id).send({'text': notification})
ChatVisualizations.objects.create(viewed = False, message = created, user = to_user)
success = str(_('The message was successfull sent!'))
return JsonResponse({"message":success})
erro = HttpResponse(str(_("No user selected!")))
erro.status_code = 404
return erro
def form_valid(self, form):
message = form.cleaned_data.get('comment')
image = form.cleaned_data.get("image")
users = (self.request.POST.get('users[]','')).split(",")
user = self.request.user
subject = self.filelink.topic.subject
if (users[0] is not ''):
for u in users:
to_user = User.objects.get(email=u)
talk, create = Conversation.objects.get_or_create(user_one=user,user_two=to_user)
created = TalkMessages.objects.create(text=message,talk=talk,user=user,subject=subject,image=image)
simple_notify = textwrap.shorten(strip_tags(message), width = 30, placeholder = "...")
if image is not '':
simple_notify += " ".join(_("[Photo]"))
notification = {
"type": "chat",
"subtype": "subject",
"space": subject.slug,
"user_icon": created.user.image_url,
"notify_title": str(created.user),
"simple_notify": simple_notify,
"view_url": reverse("chat:view_message", args = (created.id, ), kwargs = {}),
"complete": render_to_string("chat/_message.html", {"talk_msg": created}, self.request),
"container": "chat-" + str(created.user.id),
"last_date": _("Last message in %s")%(formats.date_format(created.create_date, "SHORT_DATETIME_FORMAT"))
}
notification = json.dumps(notification)
Group("user-%s" % to_user.id).send({'text': notification})
ChatVisualizations.objects.create(viewed = False, message = created, user = to_user)
success = str(_('The message was successfull sent!'))
return JsonResponse({"message":success})
erro = HttpResponse(str(_("No user selected!")))
erro.status_code = 404
return erro