Mercurial > public > sg101
diff core/functions.py @ 964:51a2051588f5
Image uploading now expects a file.
Refactor image uploading to not expect a Django UploadedFile and use a regular
file instead. This will be needed for the future feature of being able to save
and upload images from the Internet.
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Wed, 02 Sep 2015 20:50:08 -0500 |
parents | 79a71b9d0a2a |
children | f5aa74dcdd7a |
line wrap: on
line diff
--- a/core/functions.py Tue Sep 01 20:33:40 2015 -0500 +++ b/core/functions.py Wed Sep 02 20:50:08 2015 -0500 @@ -1,9 +1,9 @@ """This file houses various core utility functions""" -from contextlib import contextmanager import datetime import logging import os import re +import tempfile from django.contrib.sites.models import Site from django.conf import settings @@ -12,15 +12,23 @@ import core.tasks -@contextmanager -def temp_open(path, mode): - """A context manager for closing and removing temporary files.""" - fp = open(path, mode) - try: - yield fp - finally: - fp.close() - os.remove(path) +class TemporaryFile(object): + """Context manager class for working with temporary files. + + The file will be closed and removed when the context is exited. + """ + def __init__(self, **kwargs): + """kwargs will be passed to mkstemp.""" + self.kwargs = kwargs + + def __enter__(self): + self.fd, self.filename = tempfile.mkstemp(**self.kwargs) + self.file = os.fdopen(self.fd, 'w+b') + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.file.close() + os.remove(self.filename) def send_mail(subject, message, from_email, recipient_list, reply_to=None, defer=True):