from django.utils import formats from django.utils.encoding import force_text from datetime import datetime, timedelta from dateutil import rrule import uuid, tempfile, zipfile, os, re # Text formatted date. *sigh* def get_week_dates(date=None): if date == None: date = formats.date_format(datetime.now(), "SHORT_DATE_FORMAT") dt = datetime.strptime(date, '%m/%d/%Y') return get_week_dates_datetime(dt=dt) def get_week_dates_datetime(dt=None): week_dates = {} weekday = dt.weekday() if weekday == 6: week_dates['start_date'] = dt else: weekday = weekday + 1 week_dates['start_date'] = dt - timedelta(days=weekday) week_dates['end_date'] = week_dates['start_date'] + timedelta(days=6) week_dates['next_week'] = week_dates['end_date'] + timedelta(days=1) week_dates['previous_week'] = week_dates['start_date'] - timedelta(days=1) return week_dates def split_loads_by_day(loads,start_date,end_date): split_loads = {} for date in rrule.rrule(rrule.DAILY,dtstart=start_date, until=end_date): if date not in split_loads: split_loads[date] = loads.filter(date=date) return split_loads # This is used to set the upload path of the document for Paperwork Objects def paperwork_user_directory_path(instance, filename): # We don't want the UUID to be too long, just enough so there aren't any # filename conflicts return 'paperwork/{:d}/'.format(instance.load.pk) + \ str(uuid.uuid4())[0:9] + filename def zip_attachments_for_loads(loads, pre_append, date): td = tempfile.TemporaryDirectory() zip_file_basename = pre_append + '-' + \ date.strftime('%m.%d.%Y') + \ '.zip' zip_file_name = td.name + '/' + zip_file_basename z = zipfile.ZipFile(zip_file_name, 'w') for l in loads: for p in l.paperwork_set.all(): if os.path.exists(p.document.path): try: exp = re.compile('\.[^.]*$', re.IGNORECASE) ext = exp.findall(p.document.path) ext = ext[0] except Exception as e: print(e) ext = '.pdf' # Get the name for the zip file zipname = l.description + '-' + l.user.identity.name + ext zipname = get_valid_filename(zipname) z.write(p.document.path, zipname) # print(p.document) # Finally close off the zip file z.close() fh = open(zip_file_name, 'rb') return (zip_file_basename, fh) def get_valid_filename(s): """ Specifically modified from django.utils.text to allow spaces in the filename. Still strips leading and trailing spaces. Specifically, leading and trailing spaces are removed and anything that is not a unicode alphanumeric, dash, underscore, or dot, is removed. >>> get_valid_filename("john's portrait in 2004.jpg") 'johns portrait in 2004.jpg' """ s = force_text(s).strip().replace(' ', '_') # Convert back to spaces once we're done because... I'm lazy return re.sub(r'(?u)[^-\w.]', '', s).replace('_', ' ')