From f62a92c21374fdd51fc3621bf343fcd86635ed84 Mon Sep 17 00:00:00 2001 From: Breno Teixeira Date: Thu, 24 Oct 2013 15:11:45 -0200 Subject: [PATCH] =?UTF-8?q?migra=C3=A7=C3=A3o=20da=20app=20'utils'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sigi/apps/utils/__init__.py | 31 ++++++++++++++ sigi/apps/utils/admin_widgets.py | 16 +++++++ sigi/apps/utils/decorators.py | 71 ++++++++++++++++++++++++++++++++ sigi/apps/utils/email.py | 33 +++++++++++++++ sigi/apps/utils/validators.py | 42 +++++++++++++++++++ 5 files changed, 193 insertions(+) create mode 100644 sigi/apps/utils/__init__.py create mode 100644 sigi/apps/utils/admin_widgets.py create mode 100644 sigi/apps/utils/decorators.py create mode 100644 sigi/apps/utils/email.py create mode 100644 sigi/apps/utils/validators.py diff --git a/sigi/apps/utils/__init__.py b/sigi/apps/utils/__init__.py new file mode 100644 index 0000000..769abaa --- /dev/null +++ b/sigi/apps/utils/__init__.py @@ -0,0 +1,31 @@ +# -*- coding: utf-8 -*- +from django.contrib import admin +from django.db import models +from unicodedata import normalize + +class SearchField(models.TextField): + def pre_save(self, model_instance, add): + search_text = [] + for field_name in self.field_names: + val = unicode(to_ascii(getattr(model_instance, field_name))) + search_text.append(val) + value = u' '.join(search_text) + setattr(model_instance, self.name, value) + return value + def __init__(self, field_names, *args, **kwargs): + self.field_names = field_names + kwargs['editable'] = False + super(self.__class__, self).__init__(*args, **kwargs) + +def to_ascii(txt, codif='utf-8'): + if not isinstance(txt, basestring): + txt = unicode(txt) + if isinstance(txt, unicode): + txt = txt.encode('utf-8') + return normalize('NFKD', txt.decode(codif)).encode('ASCII','ignore') + +def queryset_ascii(self, request): + if 'q' in request.GET: + request.GET._mutable = True + request.GET['q'] = to_ascii(request.GET['q']) + return admin.ModelAdmin.queryset(self, request) diff --git a/sigi/apps/utils/admin_widgets.py b/sigi/apps/utils/admin_widgets.py new file mode 100644 index 0000000..3590a2b --- /dev/null +++ b/sigi/apps/utils/admin_widgets.py @@ -0,0 +1,16 @@ +from django.contrib.admin.widgets import AdminFileWidget +from django.utils.translation import ugettext as _ +from django.utils.safestring import mark_safe + +class AdminImageWidget(AdminFileWidget): + def render(self, name, value, attrs=None): + output = [] + if value and getattr(value, "url", None): + image_url = value.url + file_name=str(value) + output.append( + u''' %s
%s''' % \ + (image_url, image_url, file_name, _('Change:'))) + output.append(super(AdminFileWidget, self).render(name, value, attrs)) + return mark_safe(u''.join(output)) diff --git a/sigi/apps/utils/decorators.py b/sigi/apps/utils/decorators.py new file mode 100644 index 0000000..736d527 --- /dev/null +++ b/sigi/apps/utils/decorators.py @@ -0,0 +1,71 @@ +# -*- coding: utf8 -*- + +""" +Script baseado no arquivo decorators.py do django 1.3. +Ele foi copiado para usar o decorador ``login_required`` +que possui o argumento ``login_url``, responsável por +redirecionar ao template de login desejado. + +No ato de atualizar o framework, esse script torna-se +obsoleto. +""" + +import urlparse +try: + from functools import wraps +except ImportError: + from django.utils.functional import wraps # Python 2.4 fallback. + +from django.conf import settings +from django.contrib.auth import REDIRECT_FIELD_NAME +from django.utils.decorators import available_attrs + + +def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): + """ + Decorator for views that checks that the user passes the given test, + redirecting to the log-in page if necessary. The test should be a callable + that takes the user object and returns True if the user passes. + """ + + def decorator(view_func): + @wraps(view_func, assigned=available_attrs(view_func)) + def _wrapped_view(request, *args, **kwargs): + if test_func(request.user): + return view_func(request, *args, **kwargs) + path = request.build_absolute_uri() + # If the login url is the same scheme and net location then just + # use the path as the "next" url. + login_scheme, login_netloc = urlparse.urlparse(login_url or + settings.LOGIN_URL)[:2] + current_scheme, current_netloc = urlparse.urlparse(path)[:2] + if ((not login_scheme or login_scheme == current_scheme) and + (not login_netloc or login_netloc == current_netloc)): + path = request.get_full_path() + from django.contrib.auth.views import redirect_to_login + return redirect_to_login(path, login_url, redirect_field_name) + return _wrapped_view + return decorator + + +def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): + """ + Decorator for views that checks that the user is logged in, redirecting + to the log-in page if necessary. + """ + actual_decorator = user_passes_test( + lambda u: u.is_authenticated(), + login_url=login_url, + redirect_field_name=redirect_field_name + ) + if function: + return actual_decorator(function) + return actual_decorator + + +def permission_required(perm, login_url=None): + """ + Decorator for views that checks whether a user has a particular permission + enabled, redirecting to the log-in page if necessary. + """ + return user_passes_test(lambda u: u.has_perm(perm), login_url=login_url) diff --git a/sigi/apps/utils/email.py b/sigi/apps/utils/email.py new file mode 100644 index 0000000..5ccda83 --- /dev/null +++ b/sigi/apps/utils/email.py @@ -0,0 +1,33 @@ +# -*- coding: utf8 -*- + +from django.template.loader import render_to_string +from django.core.mail import EmailMessage +from django.conf import settings + + +def enviar_email(from_email, subject, template, tags): + """Envia o email para o destinatário definido, a partir do template + definido para ser renderizado. Os argumentos são: + * from_email - Email do remetente + * subject - Assunto da Mensagem + * template - Template que será usado para gerar o corpo + da mensagem + * tags - Variáveis de contexto para ser renderizado no + template. + """ + if from_email is None: + raise ValueError("Insira o email do remetente.") + elif subject is None: + raise ValueError("Insira o assunto da mensagem.") + elif template is None: + raise ValueError(u"Template da mensagem não encontrado") + elif tags is None: + raise ValueError("Insira o conteúdo da mensagem.") + + # Gerando a mensagem + mensagem = render_to_string(template, tags) + + # Enviando a mensagem + email = EmailMessage(settings.EMAIL_SUBJECT_PREFIX + " " + subject, mensagem, + from_email, [from_email]) + email.send() diff --git a/sigi/apps/utils/validators.py b/sigi/apps/utils/validators.py new file mode 100644 index 0000000..fcfc8f7 --- /dev/null +++ b/sigi/apps/utils/validators.py @@ -0,0 +1,42 @@ +# -*- coding: utf8 -*- + + +def valida_data(data_inicio, data_final): + """Função responsável por validar se o intervalo das + datas estão erradas, ou seja, se a data de início está + maior ou igual a data final. + + Caso seja maior ou igual retornará ``True``, caso contrário + retornará ``False``. + """ + if data_inicio >= data_final: + return True + else: + return False + + +def valida_periodo_data(di01, df01, di02, df02): + """Função responsável por validar dois períodos de datas. + Isso é usado para verificar se determinado servidor exerceu + mais de uma função dentro de determinados períodos descritos + abaixo: + + 1 - A segunda função não pode ter exercido ao mesmo tempo que + a primeira função. Exemplo: + + Primeiro Função: 01/05/2011 -- 01/11/2011 + Segundo Função: 01/05/2011 -- 01/11/2011 + + 2 - A segunda função não pode ter exercido, dentro do período + da primeira função. Exemplo: + + Primeira Função: 01/05/2011 -- 01/11/2011 + Segunda Função: 02/05/2011 -- 30/10/2011 + """ + # Verificando a primeira situação + if di01 == di02 and df01 == df02: + return True + elif ((di01 >= di02) or (di02 <= df01)) and df01 <= df02: + return True + else: + return False