blob: 11af6ca5c025d3e62a363ec648bc7e6a4730aa00 [file] [log] [blame]
# Copyright 2014 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""HTTP-related but otherwise miscellaneous utilities."""
import re
import urlparse
def schemeRelativeURL(absolute_url):
"""Constructs a scheme-relative URL from an absolute URL.
Args:
absolute_url: Any absolute URL.
Returns:
A scheme-relative URL identifying the same resource as the given
absolute URL.
"""
scheme = urlparse.urlparse(absolute_url)[0]
return absolute_url[len(scheme) + 1:]
INT_REGEXP = re.compile(r'^-?[0-9]+$')
def getInt(querydict, key, default=None):
"""Retrieves an integer value from a QueryDict.
Retrieves an integer value from a QueryDict (the Django
representation of HTTP request query parameters).
Args:
querydict: A Django QueryDict object, usually request.GET or request.POST.
key: The key to retrieve.
default: The default value if no key exists.
Returns:
The int() converted value of the specified query parameter if it
exists and can be successfuly converted, otherwise the specified
default value.
If the specified default is not an int, it will be returned
anyway.
"""
value = querydict.get(key, default)
if type(value) == int:
# already an integer, just return it
return value
elif type(value) == str or type(value) == unicode:
# we use a regexp here instead of .isdigit() because .isdigit()
# will return "unexpected" positives with unicode strings.
if re.match(INT_REGEXP, value):
try:
return int(value)
except ValueError:
pass
return default