Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

vigiboard / vigiboard / lib / dateformat.py @ 2bcebf54

History | View | Annotate | Download (2.8 KB)

1
# -*- coding: utf-8 -*-
2
# Copyright (C) 2006-2016 CS-SI
3
# License: GNU GPL v2 <http://www.gnu.org/licenses/gpl-2.0.html>
4

    
5
"""
6
Validateur et convertisseur de dates selon un format.
7
"""
8
from formencode.api import FancyValidator, Invalid
9
from datetime import datetime
10

    
11
from pylons.i18n import ugettext as _
12

    
13
def get_calendar_lang():
14
    from tg.i18n import get_lang
15
    import tg
16

    
17
    # TODO: Utiliser le champ "language" du modèle pour cet utilisateur ?
18
    # On récupère la langue du navigateur de l'utilisateur
19
    lang = get_lang()
20
    if not lang:
21
        lang = tg.config['lang']
22
    else:
23
        lang = lang[0]
24

    
25
    # TODO: Il faudrait gérer les cas où tout nous intéresse dans "lang".
26
    # Si l'identifiant de langage est composé (ex: "fr_FR"),
27
    # on ne récupère que la 1ère partie.
28
    lang = lang.replace('_', '-')
29
    lang = lang.split('-')[0]
30
    return lang
31

    
32
def get_date_format():
33
    # @HACK: nécessaire car l_() retourne un object LazyString
34
    # qui n'est pas sérialisable en JSON.
35
    # TRANSLATORS: Format de date et heure Python/JavaScript.
36
    # TRANSLATORS: http://www.dynarch.com/static/jscalendar-1.0/doc/html/reference.html#node_sec_5.3.5
37
    # TRANSLATORS: http://docs.python.org/release/2.5/lib/module-time.html
38
    return _('%Y-%m-%d %I:%M:%S %p').encode('utf-8')
39

    
40
class DateFormatConverter(FancyValidator):
41
    """
42
    Valide une date selon un format identique à ceux
43
    acceptés par la fonction strptime().
44
    """
45
    messages = {
46
        'invalid': 'Invalid value',
47
    }
48

    
49
    def _to_python(self, value, state):
50
        if not isinstance(value, basestring):
51
            raise Invalid(self.message('invalid', state), value, state)
52

    
53
        str_date = value.lower()
54
        if isinstance(str_date, unicode):
55
            str_date = str_date.encode('utf-8')
56

    
57
        try:
58
            # On tente d'interpréter la saisie de l'utilisateur
59
            # selon un format date + heure.
60
            date = datetime.strptime(str_date, get_date_format())
61
        except ValueError:
62
            try:
63
                # 2è essai : on essaye d'interpréter uniquement une date.
64
                # TRANSLATORS: Format de date Python/JavaScript.
65
                # TRANSLATORS: http://www.dynarch.com/static/jscalendar-1.0/doc/html/reference.html#node_sec_5.3.5
66
                # TRANSLATORS: http://docs.python.org/release/2.5/lib/module-time.html
67
                date = datetime.strptime(str_date, _('%Y-%m-%d').encode('utf8'))
68
            except ValueError:
69
                raise Invalid(self.message('invalid', state), value, state)
70
        return date
71

    
72
    def _from_python(self, value, state):
73
        if not isinstance(value, datetime):
74
            raise Invalid(self.message('invalid', state), value, state)
75

    
76
        # Même format que pour _to_python.
77
        return datetime.strftime(value, get_date_format()).decode('utf-8')