Statistics
| Branch: | Tag: | Revision:

root / snf-django-lib / snf_django / lib / api / parsedate.py @ c7e03d20

History | View | Annotate | Download (3.5 kB)

1
# Copyright (c) Django Software Foundation and individual contributors.
2
# All rights reserved.
3
#
4
# Redistribution and use in source and binary forms, with or without
5
# modification, are permitted provided that the following conditions are met:
6
#
7
#     1. Redistributions of source code must retain the above copyright notice,
8
#        this list of conditions and the following disclaimer.
9
#
10
#     2. Redistributions in binary form must reproduce the above copyright
11
#        notice, this list of conditions and the following disclaimer in the
12
#        documentation and/or other materials provided with the distribution.
13
#
14
#     3. Neither the name of Django nor the names of its contributors may be
15
#        used to endorse or promote products derived from this software without
16
#        specific prior written permission.
17
#
18
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
22
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28

    
29
import re
30
import datetime
31
import calendar
32

    
33
MONTHS = 'jan feb mar apr may jun jul aug sep oct nov dec'.split()
34
__D = r'(?P<day>\d{2})'
35
__D2 = r'(?P<day>[ \d]\d)'
36
__M = r'(?P<mon>\w{3})'
37
__Y = r'(?P<year>\d{4})'
38
__Y2 = r'(?P<year>\d{2})'
39
__T = r'(?P<hour>\d{2}):(?P<min>\d{2}):(?P<sec>\d{2})'
40
RFC1123_DATE = re.compile(r'^\w{3}, %s %s %s %s GMT$' % (__D, __M, __Y, __T))
41
RFC850_DATE = re.compile(r'^\w{6,9}, %s-%s-%s %s GMT$' % (__D, __M, __Y2, __T))
42
ASCTIME_DATE = re.compile(r'^\w{3} %s %s %s %s$' % (__M, __D2, __T, __Y))
43

    
44

    
45
def parse_http_date(date):
46
    """
47
    Parses a date format as specified by HTTP RFC2616 section 3.3.1.
48

49
    The three formats allowed by the RFC are accepted, even if only the first
50
    one is still in widespread use.
51

52
    Returns an floating point number expressed in seconds since the epoch, in
53
    UTC.
54
    """
55
    # emails.Util.parsedate does the job for RFC1123 dates; unfortunately
56
    # RFC2616 makes it mandatory to support RFC850 dates too. So we roll
57
    # our own RFC-compliant parsing.
58
    for regex in RFC1123_DATE, RFC850_DATE, ASCTIME_DATE:
59
        m = regex.match(date)
60
        if m is not None:
61
            break
62
    else:
63
        raise ValueError("%r is not in a valid HTTP date format" % date)
64
    try:
65
        year = int(m.group('year'))
66
        if year < 100:
67
            if year < 70:
68
                year += 2000
69
            else:
70
                year += 1900
71
        month = MONTHS.index(m.group('mon').lower()) + 1
72
        day = int(m.group('day'))
73
        hour = int(m.group('hour'))
74
        min = int(m.group('min'))
75
        sec = int(m.group('sec'))
76
        result = datetime.datetime(year, month, day, hour, min, sec)
77
        return calendar.timegm(result.utctimetuple())
78
    except Exception:
79
        raise ValueError("%r is not a valid date" % date)
80

    
81

    
82
def parse_http_date_safe(date):
83
    """
84
    Same as parse_http_date, but returns None if the input is invalid.
85
    """
86
    try:
87
        return parse_http_date(date)
88
    except Exception:
89
        pass