Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

vigiboard / vigiboard / lib / dateformat.py @ 011743be

History | View | Annotate | Download (2.79 KB)

1
# -*- coding: utf-8 -*-
2
# Copyright (C) 2006-2020 CS GROUP - France
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 tg.i18n import ugettext as _, get_lang
12

    
13
def get_calendar_lang():
14
    import tg
15

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

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

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

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

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

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

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

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

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