Source for utils/__init__.py
2011-08-18 18:13:16 / 5.0 Kt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 | # -*- coding: utf-8 -*- """ General utilities. Copyright (C) 2010, 2011 Jyrki Launonen This file is part of slavemaster. Slavemaster 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. Slavemaster 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 Slavemaster. If not, see <http://www.gnu.org/licenses/>. """ from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse __all__ = [ "requireLogin", "getFormPost", "copyFromModelField", "getFullEmailAddress", "createDirDict", "assignDirectory", "getAge", ] def checkUserModel(request): """Check the user profile. Will return None if profile exists, and HttpResponseRedirect -object to user info if profile does not exist. """ from accounts.models import User try: User.objects.only('id').get(account = request.user) except User.DoesNotExist: return HttpResponseRedirect(reverse('user_changeinfo')) return None def requireLogin(function): """Alternative decorator for login_required. This checks that user profile exists too (using checkUserModel()). """ @login_required def wrapper(request, *args, **kwargs): return checkUserModel(request) or function(request, *args, **kwargs) return wrapper def getFormPost(form, request, *args, **kwargs): """Return form instance regardless of method. If method is POST, fill form with request data. """ if request.method == "POST": return form(request.POST, *args, **kwargs) else: return form(*args, **kwargs) # def copyFromModelField(model, field, *args, **kwargs): """Copies given properties from field of model by returning a dictionary filled with the properties. Optional kwargs renames properties from given key in field to given value in result. Use of this might be obsolete in Django =>1.2 due to additional form.Meta settings (widget, etc). """ field = model._meta.get_field(field) ret = {} for name in list(args) + kwargs.keys(): target = name if name not in kwargs else kwargs[name] ret[target] = getattr(field, name) return ret def getFullEmailAddress(user): """Get full formatted email address for user (may be either DjangoUser or accounts.User).""" from django.contrib.auth.models import User as DjangoUser from accounts.models import formatUserName if not isinstance(user, DjangoUser): user = user.account return u"{0} <{1}>".format( formatUserName(user.first_name, user.last_name, user.username), user.email, ) # Okay, formataddr fails unicode. #return formataddr((unicode(user), user.email)) # def createDirDict(*args, **kwargs): """Create a 'class' directory from given functions. Note that all decorated functions need to be specified in kwargs for them to work.""" ret = dict() for func in args: ret[func.__name__] = func for key, value in kwargs.iteritems(): ret[key] = value return ret def assignDirectory(directory): """Assigns given function directory to a class. Example: def hello(self): print "Hello method" @assignDirectory(createDirDict(hello)) class Cls(): pass Cls().hello() """ def assignTo(classObject): for key, value in directory.iteritems(): setattr(classObject, key, value) return classObject return assignTo """ import datetime from utils import getAge getAge(datetime.date(1983, 11, 1)) getAge(datetime.date(1983, 11, 1), asFloat = True) """ def getAge(birthday, today = None, asFloat = False): import datetime if today is None: today = datetime.date.today() age = today.year - birthday.year bd_thisY = birthday.replace(year = today.year) ageD = (today - bd_thisY).days #print ageD, bd_thisY if ageD < 0: # Current date is before birthday on this year. age -= 1 if asFloat: age = float(age) if ageD == 0: # Birthday is today \o/ return age if ageD < 0: # cur is before Bd. Near = previous year. near_bd = birthday.replace(year = today.year - 1) else: # cur is after Bd. Near = next year. near_bd = birthday.replace(year = today.year + 1) near_bd = birthday.replace(year = (today.year - 1) if ageD < 0 else (today.year + 1)) year_days = float( (near_bd - bd_thisY).days ) past = year_days - float( (near_bd - today).days ) #print age, past, year_days, near_bd return age + abs(past / year_days) return age # |