Skip to content

Instantly share code, notes, and snippets.

@gabrielhurley
Created November 26, 2011 03:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabrielhurley/1394909 to your computer and use it in GitHub Desktop.
Save gabrielhurley/1394909 to your computer and use it in GitHub Desktop.
Django Convenience Utility Functions
# Copyright 2011 Gabriel Hurley <gabriel@strikeawe.com>
#
# Licensed under the OSI-approved Fair License:
#
# Usage of this work is permitted provided that this
# instrument is retained with the work, so that any
# entity that uses the work is notified of this instrument.
#
# DISCLAIMER: THIS WORK IS WITHOUT WARRANTY.
import threading
from datetime import datetime, timedelta
from django.conf import settings
from django.http import HttpResponse
from django.utils import simplejson as json
from django.utils.dateformat import format, time_format
def send_threaded(msg, fail_silently=True, *args):
""" Sends an email message in a new thread.
Example::
from django.core.mail import EmailMessage
email = EmailMessage('Hello',
'Body goes here',
'from@example.com',
['to@example.com'])
send_threaded(email)
...
That will cause the email to be sent and the surrounding code
can continue executing without waiting for the email server
to process the message.
"""
t = threading.Thread(target=msg.send,
args=args,
kwargs={'fail_silently': fail_silently})
t.setDaemon(True)
t.start()
def relative_time(input):
"""
Returns a time-formatter string for times less than 12 hours
from now, or a date for times greater than 12 hours from now.
"""
if datetime.now() - input < timedelta(.5):
return time_format(input, settings.TIME_FORMAT)
else:
return format(input, settings.DATE_FORMAT)
def render_to_json(data):
""" Returns an HttpResponse containing the JSON-formatter data. """
json_data = json.dumps(data, ensure_ascii=False)
return HttpResponse(json_data, mimetype="application/json")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment