1"""Copyright 2008 Orbitz WorldWide
2
3Licensed under the Apache License, Version 2.0 (the "License");
4you may not use this file except in compliance with the License.
5You may obtain a copy of the License at
6
7     http://www.apache.org/licenses/LICENSE-2.0
8
9Unless required by applicable law or agreed to in writing, software
10distributed under the License is distributed on an "AS IS" BASIS,
11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12See the License for the specific language governing permissions and
13limitations under the License."""
14import calendar
15import hashlib
16import pytz
17
18from flask import request
19
20
21def is_pattern(s):
22    return '*' in s or '?' in s or '[' in s or '{' in s
23
24
25class RequestParams(object):
26    """Dict-like structure that allows accessing request params
27    whatever their origin (json body, form body, request args)."""
28
29    def __getitem__(self, key):
30        if request.json and key in request.json:
31            return request.json[key]
32        if key in request.form:
33            return request.form.getlist(key)[-1]
34        if key in request.args:
35            return request.args.getlist(key)[-1]
36        raise KeyError
37
38    def __contains__(self, key):
39        try:
40            self[key]
41            return True
42        except KeyError:
43            return False
44
45    def get(self, key, default=None):
46        try:
47            return self[key]
48        except KeyError:
49            return default
50
51    def getlist(self, key):
52        if request.json and key in request.json:
53            value = self[key]
54            if not isinstance(value, list):
55                value = [value]
56            return value
57        if key in request.form:
58            return request.form.getlist(key)
59        return request.args.getlist(key)
60RequestParams = RequestParams()
61
62
63def hash_request():
64    keys = set()
65    if request.json:
66        keys.update(request.json.keys())
67    if request.form:
68        keys.update(request.form.keys())
69    keys.update(request.args.keys())
70    params = u",".join([
71        u"{0}={1}".format(key, u"&".join(sorted(RequestParams.getlist(key))))
72        for key in sorted(keys) if not key.startswith('_')
73    ])
74    md5 = hashlib.md5()
75    md5.update(params.encode('utf-8'))
76    return md5.hexdigest()
77
78
79def to_seconds(delta):
80    return abs(delta.seconds + delta.days * 86400)
81
82
83def epoch(dt):
84    """
85    Returns the epoch timestamp of a timezone-aware datetime object.
86    """
87    return calendar.timegm(dt.astimezone(pytz.utc).timetuple())
88