Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

vigiboard / vigiboard / lib / dateformat.py @ 8d647d93

History | View | Annotate | Download (2.35 KB)

1
# -*- coding: utf-8 -*-
2
# Copyright (C) 2006-2015 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
    return _('%Y-%m-%d %I:%M:%S %p').encode('utf-8')
36

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

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

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

    
54
        try:
55
            # TRANSLATORS: Format de date et heure Python/JavaScript.
56
            # TRANSLATORS: http://www.dynarch.com/static/jscalendar-1.0/doc/html/reference.html#node_sec_5.3.5
57
            # TRANSLATORS: http://docs.python.org/release/2.5/lib/module-time.html
58
            date = datetime.strptime(str_date, _('%Y-%m-%d %I:%M:%S %p').encode('utf8'))
59
        except ValueError:
60
            raise Invalid(self.message('invalid', state), value, state)
61
        return date
62

    
63
    def _from_python(self, value, state):
64
        if not isinstance(value, datetime):
65
            raise Invalid(self.message('invalid', state), value, state)
66

    
67
        # Même format que pour _to_python.
68
        return datetime.strftime(
69
                    value,
70
                    _('%Y-%m-%d %I:%M:%S %p').encode('utf8')
71
                ).decode('utf-8')