fargo/fargo/fargo/utils.py

61 lines
1.6 KiB
Python

# fargo - document box
# Copyright (C) 2016-2019 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import hashlib
from django.apps import apps
from django.utils.timezone import utc
try:
import magic
except ImportError:
magic = None
def to_isodate(dt):
return dt.astimezone(utc).isoformat('T').split('.')[0] + 'Z'
def sha256_of_file(f):
'''Compute SHA-256 hash of Django File object'''
hasher = hashlib.sha256()
for chunk in f.chunks():
hasher.update(chunk)
return hasher.hexdigest()
def get_mime_type(fd):
if magic is None:
return None
mime_type = magic.from_buffer(next(fd.chunks(1024 * 20)), mime=True)
if mime_type:
mime_type = mime_type.split(';')[0]
if mime_type.startswith('cannot open'):
mime_type = None
return mime_type
def cleanup_model(model, n=None):
manager = getattr(model, 'objects', None)
if hasattr(manager, 'cleanup'):
manager.cleanup(n=n)
def cleanup(n=None):
for model in apps.get_models():
cleanup_model(model, n=n)