src/ldt/ldt/utils/url.py
author ymh <ymh.work@gmail.com>
Fri, 24 May 2013 02:20:46 +0200
changeset 1194 8e20df96315b
parent 1187 73403060f297
child 1398 f40668870c7a
permissions -rw-r--r--
correct rest api resource after tastypie and django update. Find a way to go around django bugs with ~ in urls

from django.contrib.staticfiles.storage import staticfiles_storage
from django.core.urlresolvers import reverse, get_script_prefix
from django.utils.encoding import iri_to_uri
from ldt.utils.web_url_management import get_web_url
from ldt import settings
from django.conf import settings as djangosettings
import httplib2
import re
import urlparse
from django.utils.http import urlquote

def static(path):
    return staticfiles_storage.url(path)

def absstatic(request, path):
    domain=get_web_url(request)
    new_path = staticfiles_storage.url(path)
    return urlparse.urljoin(domain, new_path)

def absolute_media_url():
    domain=get_web_url()
    
    return urlparse.urljoin(domain, djangosettings.MEDIA_URL)

def absurl(request, viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None):
    domain=get_web_url(request)
    path=reverse(viewname, urlconf, args, kwargs, prefix, current_app)
    return urlparse.urljoin(domain, path)

def absurl_norequest(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None):
    domain=get_web_url()
    path=reverse(viewname, urlconf, args, kwargs, prefix, current_app)
    return urlparse.urljoin(domain, path)

def request_with_auth(url, method='GET'):
    h = httplib2.Http()
    web_auth = settings.WEB_AUTH if settings.WEB_AUTH else []
    for entry in web_auth:
        if not isinstance(entry, dict):
            continue
        regex = entry.get('REGEX', None)
        if regex and re.search(regex, url, re.IGNORECASE):
            h.add_credentials(entry.get('NAME', ''), entry.get('PASSWORD', ''), entry.get('DOMAIN', ''))
            break
            
    return h.request(url, method)


def is_absolute(url):
    return bool(urlparse.urlparse(url).scheme)

###
# 
#
def reverse_prefix(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None):
    
    url = reverse(viewname,urlconf,args,kwargs,prefix,current_app)
    prefix = get_script_prefix()
    quoted_prefix = urlquote(prefix)
    clean_prefix = iri_to_uri(prefix)
    
    if url.startswith(quoted_prefix):
        return clean_prefix + url[len(quoted_prefix):]
    else:
        return url