예제 #1
0
 def _redirect(self, request, secure):
     protocol = secure and 'https' or 'http'
     if secure:
         host = HTTPS_HOST or get_host(request)
     else:
         host = HTTP_HOST or get_host(request)
     url = '%s://%s%s' % (protocol, host, request.get_full_path())
     if settings.DEBUG and request.method == 'POST':
         raise RuntimeError, "Django can't perform an SSL redirect while " \
             + "maintaining POST data. Please structure your views so " \
             + "that redirects only occur during GETs."
     return HttpResponseRedirect(url)
예제 #2
0
    def _redirect(self, request, secure):
        protocol = secure and "https" or "http"
        if secure:
            host = getattr(settings, 'SSL_HOST', get_host(request))
        else:
            host = getattr(settings, 'HTTP_HOST', get_host(request))
        newurl = "%s://%s%s" % (protocol,host,request.get_full_path())
        if settings.DEBUG and request.method == 'POST':
            raise RuntimeError, \
        """Django can't perform a SSL redirect while maintaining POST data.
           Please structure your views so that redirects only occur during GETs."""

        return HttpResponseRedirect(newurl)
예제 #3
0
 def process_response(self, request, response):
     if isinstance(response, HttpResponseRedirect):
         path = response["Location"]
         if path.startswith("/"):
             response["Location"] = "https://%s%s" % (get_host(request), 
                 path)
         elif path.startswith("http:"):
             if get_host(request) in path:
                 response["Location"] = path.replace("http:", "https:")
         else:
             response["Location"] = "https://%s%s%s" % (get_host(request),
                 request.path_info, path)
     return response
예제 #4
0
def _logout_url(request, next_page=None):
    url = urljoin(settings.CALNET_SERVER_URL, "logout")
    if next_page:
        protocol = ("http://", "https://")[request.is_secure()]
        host = get_host(request)
        url += "?" + urlencode({"url": protocol + host + next_page})
    return url
예제 #5
0
def _redirect_url(request):
    """ Redirects to referring page """
    next_page = request.META.get("HTTP_REFERER")
    prefix = ("http://", "https://")[request.is_secure()] + get_host(request)
    if next_page and next_page.startswith(prefix):
        next_page = next_page[len(prefix) :]
    return next_page
예제 #6
0
 def _redirect(self, request, secure):
     protocol = "https" if secure else "http"
     url = "%s://%s%s" % (protocol, get_host(request), request.get_full_path())
     if settings.DEBUG and request.method == "POST":
         raise RuntimeError, """Django can't perform a SSL redirect while maintaining POST data.
        Structure your views so that redirects only occur during GETs."""
     return HttpResponsePermanentRedirect(url)
예제 #7
0
파일: views.py 프로젝트: kevinr/750book-web
def get_url_host(request):
    if request.is_secure():
        protocol = "https"
    else:
        protocol = "http"
    host = escape(get_host(request))
    return "%s://%s" % (protocol, host)
예제 #8
0
파일: views.py 프로젝트: hifans/CNPROG
def get_url_host(request):
    if request.is_secure():
        protocol = "https"
    else:
        protocol = "http"
    host = escape(get_host(request))
    return "%s://%s" % (protocol, host)
예제 #9
0
파일: common.py 프로젝트: alatteri/informer
    def process_response(self, request, response):
        "Check for a flat page (for 404s) and calculate the Etag, if needed."
        if response.status_code == 404:
            if settings.SEND_BROKEN_LINK_EMAILS:
                # If the referrer was from an internal link or a non-search-engine site,
                # send a note to the managers.
                domain = http.get_host(request)
                referer = request.META.get('HTTP_REFERER', None)
                is_internal = _is_internal_request(domain, referer)
                path = request.get_full_path()
                if referer and not _is_ignorable_404(path) and (is_internal or '?' not in referer):
                    ua = request.META.get('HTTP_USER_AGENT', '<none>')
                    ip = request.META.get('REMOTE_ADDR', '<none>')
                    mail_managers("Broken %slink on %s" % ((is_internal and 'INTERNAL ' or ''), domain),
                        "Referrer: %s\nRequested URL: %s\nUser agent: %s\nIP address: %s\n" \
                                  % (referer, request.get_full_path(), ua, ip))
                return response

        # Use ETags, if requested.
        if settings.USE_ETAGS:
            if response.has_header('ETag'):
                etag = response['ETag']
            else:
                etag = md5.new(response.content).hexdigest()
            if response.status_code >= 200 and response.status_code < 300 and request.META.get('HTTP_IF_NONE_MATCH') == etag:
                response = http.HttpResponseNotModified()
            else:
                response['ETag'] = etag

        return response
예제 #10
0
파일: views.py 프로젝트: Almad/pinax
def details(request, id, template_name="photos/details.html", group_slug=None, bridge=None):
    """
    show the photo details
    """
    
    if bridge:
        try:
            group = bridge.get_group(group_slug)
        except ObjectDoesNotExist:
            raise Http404
    else:
        group = None
    
    # @@@ group support
    photo = get_object_or_404(Image, id=id)
    # @@@: test
    if not photo.is_public and request.user != photo.member:
        raise Http404
    photo_url = photo.get_display_url()
    
    title = photo.title
    host = "http://%s" % get_host(request)
    
    if photo.member == request.user:
        is_me = True
    else:
        is_me = False
    
    return render_to_response(template_name, {
        "group": group,
        "host": host, 
        "photo": photo,
        "photo_url": photo_url,
        "is_me": is_me,
    }, context_instance=RequestContext(request))
예제 #11
0
 def process_request(self, request):
     """
     Process an incoming HTTP GET or HEAD request.
     """
     # Don't rewrite POST requests
     if not request.method in ('GET', 'HEAD'):
         return
     parts = request.path.strip('/').split('/')
     first_part = parts[0]
     last_part = parts[-1]
     # Redirect to XML-RPC documentation
     host = http.get_host(request)
     subdomain = host.lower().split('.')[0]
     if subdomain in ('api', 'xmlrpc') and first_part == '':
         return http.HttpResponsePermanentRedirect('/xmlrpc/')
     # Fix double slash after http: or https:
     if first_part in ('http:', 'https:') and len(parts) >= 2 and parts[1]:
         new_path = request.get_full_path().replace(':/', '://', 1)
         return http.HttpResponsePermanentRedirect(new_path)
     # Add trailing slash if path starts with an installed app name
     if request.path.endswith('/') or not self.installed_app(first_part):
         return
     # Don't add trailing slash after filenames
     if '.' in last_part and first_part != 'xmlrpc':
         return
     new_path = request.path + '/'
     if request.GET:
         new_path += '?' + request.GET.urlencode()
     return http.HttpResponsePermanentRedirect(new_path)
예제 #12
0
파일: common.py 프로젝트: alatteri/informer
    def process_request(self, request):
        """
        Check for denied User-Agents and rewrite the URL based on
        settings.APPEND_SLASH and settings.PREPEND_WWW
        """

        # Check for denied User-Agents
        if 'HTTP_USER_AGENT' in request.META:
            for user_agent_regex in settings.DISALLOWED_USER_AGENTS:
                if user_agent_regex.search(request.META['HTTP_USER_AGENT']):
                    return http.HttpResponseForbidden('<h1>Forbidden</h1>')

        # Check for a redirect based on settings.APPEND_SLASH and settings.PREPEND_WWW
        host = http.get_host(request)
        old_url = [host, request.path]
        new_url = old_url[:]
        if settings.PREPEND_WWW and old_url[0] and not old_url[0].startswith('www.'):
            new_url[0] = 'www.' + old_url[0]
        # Append a slash if append_slash is set and the URL doesn't have a
        # trailing slash or a file extension.
        if settings.APPEND_SLASH and (old_url[1][-1] != '/') and ('.' not in old_url[1].split('/')[-1]):
            new_url[1] = new_url[1] + '/'
            if settings.DEBUG and request.method == 'POST':
                raise RuntimeError, "You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to %s%s (note the trailing slash), or set APPEND_SLASH=False in your Django settings." % (new_url[0], new_url[1])
        if new_url != old_url:
            # Redirect
            if new_url[0]:
                newurl = "%s://%s%s" % (request.is_secure() and 'https' or 'http', new_url[0], new_url[1])
            else:
                newurl = new_url[1]
            if request.GET:
                newurl += '?' + request.GET.urlencode()
            return http.HttpResponsePermanentRedirect(newurl)

        return None
예제 #13
0
파일: views.py 프로젝트: amarandon/pinax
def details(request, id, template_name="photos/details.html"):
    """
    show the photo details
    """

    group, bridge = group_and_bridge(request)

    photos = Image.objects.all()

    if group:
        photos = group.content_objects(photos, join="pool", gfk_field="content_object")
    else:
        photos = photos.filter(pool__object_id=None)

    photo = get_object_or_404(photos, id=id)

    # @@@: test
    if not photo.is_public and request.user != photo.member:
        raise Http404

    photo_url = photo.get_display_url()

    title = photo.title
    host = "http://%s" % get_host(request)

    if photo.member == request.user:
        is_me = True
    else:
        is_me = False

    ctx = group_context(group, bridge)
    ctx.update({"host": host, "photo": photo, "photo_url": photo_url, "is_me": is_me})

    return render_to_response(template_name, RequestContext(request, ctx))
예제 #14
0
 def process_request(self, request):
     """
     Process an incoming HTTP GET or HEAD request.
     """
     # Don't rewrite POST requests
     if not request.method in ('GET', 'HEAD'):
         return
     parts = request.path.strip('/').split('/')
     first_part = parts[0]
     last_part = parts[-1]
     # Redirect to XML-RPC documentation
     host = http.get_host(request)
     subdomain = host.lower().split('.')[0]
     if subdomain in ('api', 'xmlrpc') and first_part == '':
         return http.HttpResponsePermanentRedirect('/xmlrpc/')
     # Fix double slash after http: or https:
     if first_part in ('http:', 'https:') and len(parts) >= 2 and parts[1]:
         new_path = request.get_full_path().replace(':/', '://', 1)
         return http.HttpResponsePermanentRedirect(new_path)
     # Add trailing slash if path starts with an installed app name
     if request.path.endswith('/') or not self.installed_app(first_part):
         return
     # Don't add trailing slash after filenames
     if '.' in last_part and first_part != 'xmlrpc':
         return
     new_path = request.path + '/'
     if request.GET:
         new_path += '?' + request.GET.urlencode()
     return http.HttpResponsePermanentRedirect(new_path)
예제 #15
0
def get_url_host(request):
    if request.is_secure():
        protocol = 'https'
    else:
        protocol = 'http'
    host = escape(get_host(request))
    return '%s://%s' % (protocol, host)
예제 #16
0
 def _redirect(self, request, secure):
     protocol = secure and "https" or "http"
     if use_request_for_host:
         newurl = "%s://%s.%s%s" % (protocol, "www", request.get_host(), request.get_full_path())
     else:
         newurl = "%s://%s.%s%s" % (protocol, "www", get_host(request), request.get_full_path())
     return HttpResponseRedirect(newurl)
예제 #17
0
파일: middleware.py 프로젝트: ezl/recs
 def _redirect(self, request):
     if settings.DEBUG and request.method == 'POST':
         raise RuntimeError(
         """Django can't perform a SSL redirect while maintaining POST data.                           
             Please structure your views so that redirects only occur during GETs.""")
     newurl = 'http://%s%s' % (get_host(request), request.get_full_path())
     return HttpResponseRedirect(newurl)
예제 #18
0
    def process_response(self, request, response):
        "Check for a flat page (for 404s) and calculate the Etag, if needed."
        if response.status_code == 404:
            if settings.SEND_BROKEN_LINK_EMAILS:
                # If the referrer was from an internal link or a non-search-engine site,
                # send a note to the managers.
                domain = http.get_host(request)
                referer = request.META.get('HTTP_REFERER', None)
                is_internal = _is_internal_request(domain, referer)
                path = request.get_full_path()
                if referer and not _is_ignorable_404(path) and (
                        is_internal or '?' not in referer):
                    ua = request.META.get('HTTP_USER_AGENT', '<none>')
                    mail_managers(
                        "Broken %slink on %s" %
                        ((is_internal and 'INTERNAL ' or ''), domain),
                        "Referrer: %s\nRequested URL: %s\nUser agent: %s\n" %
                        (referer, request.get_full_path(), ua))
                return response

        # Use ETags, if requested.
        if settings.USE_ETAGS:
            etag = md5(response.content).hexdigest()
            if request.META.get('HTTP_IF_NONE_MATCH') == etag:
                response = http.HttpResponseNotModified()
            else:
                response['ETag'] = etag

        return response
예제 #19
0
파일: views.py 프로젝트: ginking/oserver
def details(request, id, template_name="photos/details.html", **kwargs):
    """
    show the photo details
    """

    group, bridge = group_and_bridge(kwargs)

    photos = Image.objects.all()

    if group:
        photos = group.content_objects(photos)
    else:
        photos = photos.filter(object_id=None)

    photo = get_object_or_404(photos, id=id)

    # @@@: test
    if not photo.is_public and request.user != photo.member:
        raise Http404

    photo_url = photo.get_display_url()
    host = "http://%s" % get_host(request)

    return {
        "TEMPLATE": template_name,
        "group": group,
        "host": host,
        "photo": photo,
        "photo_url": photo_url,
        "is_me": photo.member == request.user,
    }
예제 #20
0
파일: middleware.py 프로젝트: garagelab/GPB
    def process_request(self, request):
        """
        Rewrite the URL based on settings.SMART_APPEND_SLASH
        """

        # Check for a redirect based on settings.SMART_APPEND_SLASH
        host = http.get_host(request)
        old_url = [host, request.path]
        new_url = old_url[:]
        # Append a slash if SMART_APPEND_SLASH is set and the resulting URL
        # resolves.
        if settings.SMART_APPEND_SLASH: 
            if (not old_url[1].endswith('/')) and not _resolves(old_url[1]) and _resolves(old_url[1] + '/'):
                new_url[1] = new_url[1] + '/'
                if settings.DEBUG and request.method == 'POST':
                    raise RuntimeError, "You called this URL via POST, but the URL doesn't end in a slash and you have SMART_APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to %s%s (note the trailing slash), or set SMART_APPEND_SLASH=False in your Django settings." % (new_url[0], new_url[1])
            else:
                if (old_url[1].endswith('/')) and _resolves(old_url[1][:-1]):
                    new_url[1] = old_url[1][:-1]
                    
            if new_url != old_url:
                # Redirect
                if new_url[0]:
                    newurl = "%s://%s%s" % (request.is_secure() and 'https' or 'http', new_url[0], new_url[1])
                else:
                    newurl = new_url[1]
                if request.GET:
                    newurl += '?' + request.GET.urlencode()
                return http.HttpResponsePermanentRedirect(newurl)

        return None
예제 #21
0
 def redirect(self, request):
     url = 'https://%s%s' % (
         get_host(request),
         request.get_full_path()
     )
     secure_url = url.replace("http://", "https://")
     return HttpResponsePermanentRedirect(secure_url)
예제 #22
0
def get_url_host(request):
# FIXME: Duplication
    if request.is_secure():
        protocol = 'https'
    else:
        protocol = 'http'
    host = get_host(request)
    return '%s://%s' % (protocol, host)
예제 #23
0
    def _redirect(self, request, use_secure):
        protocol = use_secure and "https" or "http"
        redirect_url = "%s://%s%s" % (protocol, get_host(request), request.get_full_path())
        if settings.DEBUG and request.method == 'POST':
            raise RuntimeError("""Django can't perform a SSL redirect while maintaining POST data.
           Please structure your views so that redirects only occur during GETs.""")

        return HttpResponsePermanentRedirect(redirect_url)
예제 #24
0
def _service_url(request, next_page):
    protocol = ("http://", "https://")[request.is_secure()]
    host = get_host(request)
    service = protocol + host + request.path
    url = service
    if next_page:
        url += "?" + urlencode({REDIRECT_FIELD_NAME: next_page})
    return url
예제 #25
0
 def _redirect(self, request, secure):
     protocol = 'https' if secure else 'http'
     url = "%s://%s%s" % (protocol, get_host(request),
                          request.get_full_path())
     if settings.DEBUG and request.method == 'POST':
         raise RuntimeError, \
     """Django can't perform a SSL redirect while maintaining POST data.
        Structure your views so that redirects only occur during GETs."""
     return HttpResponsePermanentRedirect(url)
예제 #26
0
 def _redirect(self, request, secure):
     protocol = secure and "https" or "http"
     if use_request_for_host:
         newurl = "%s://%s.%s%s" % (protocol, 'www', request.get_host(),
                                    request.get_full_path())
     else:
         newurl = "%s://%s.%s%s" % (protocol, 'www', get_host(request),
                                    request.get_full_path())
     return HttpResponseRedirect(newurl)
예제 #27
0
def _redirect(request, secure):
    protocol = secure and "https" or "http"
    newurl = "%s://%s%s" % (protocol, get_host(request), request.get_full_path())
    if getattr(settings, 'SSL_ENABLED', False):
        if settings.DEBUG and request.method == 'POST':
            raise RuntimeError("Django can't perform a redirect while maintaining POST data.")
        return HttpResponsePermanentRedirect(newurl)
    else:
        return None
예제 #28
0
파일: views.py 프로젝트: keokilee/makahiki
def _logout_url(request, next_page=None):
    """Generates CAS logout URL"""

    url = urljoin(settings.CAS_SERVER_URL, 'logout')
    if next_page:
        protocol = ('http://', 'https://')[request.is_secure()]
        host = get_host(request)
        url += '?' + urlencode({'service': protocol + host + next_page})
    return url
예제 #29
0
    def _redirect(self, request):
        newurl = "https://%s%s" % (get_host(request), request.get_full_path())
        if settings.DEBUG and request.method == 'POST':
            raise RuntimeError(
                "Django can't perform a SSL redirect while maintaining POST "
                "data. Please structure your views so that redirects only "
                "occur during GETs.")

        return HttpResponseTemporaryRedirect(newurl)
예제 #30
0
파일: views.py 프로젝트: sicikle/django-sis
def _logout_url(request, next_page=None):
    """Generates CAS logout URL"""

    url = urljoin(settings.CAS_SERVER_URL, "logout")
    if next_page:
        protocol = ("http://", "https://")[request.is_secure()]
        host = get_host(request)
        url += "?" + urlencode({"service": protocol + host})
    return url
예제 #31
0
 def process_request(self, request):
     host = get_host(request)
     if host and host.startswith('www.'):
         newurl = "%s://%s%s" % (request.is_secure() and 'https' or 'http', host[len('www.'):], request.path)
         if request.GET:
             newurl += '?' + request.GET.urlencode()
         return HttpResponsePermanentRedirect(newurl)
     else:
         return None
예제 #32
0
 def process_request(self, request):
     host = get_host(request)
     if host and host.startswith('www.'):
         newurl = "%s://%s%s" % (request.is_secure() and 'https' or 'http',
                                 host[len('www.'):], request.path)
         if request.GET:
             newurl += '?' + request.GET.urlencode()
         return redirect(newurl, permaent=True)
     else:
         return None
예제 #33
0
파일: x_ssl.py 프로젝트: bwinton/ispdb
    def _redirect(self, request, secure):
        protocol = secure and "https" or "http"
        newurl = "%s://%s%s" % (protocol,get_host(request),request.get_full_path())
        if settings.DEBUG and request.method == 'POST':
            raise RuntimeError, \
"""Django can't perform a SSL redirect while maintaining POST data.
Please structure your views so that redirects only occur during GETs."""

        #return HttpResponseRedirect(newurl)
        return HttpResponsePermanentRedirect(newurl) #I have not had time to test this, but it appears to work better.
예제 #34
0
파일: views.py 프로젝트: bkuhn/podjango
def relative_redirect(request, path):
    from django import http
    from django.conf import settings

    host = http.get_host(request)
    if settings.FORCE_CANONICAL_HOSTNAME:
        host = settings.FORCE_CANONICAL_HOSTNAME

    url = "%s://%s%s" % (request.is_secure() and 'https' or 'http', host, path)
    return http.HttpResponseRedirect(url)
예제 #35
0
 def _redirect(self, request, secure):
     if settings.DEBUG and request.method == 'POST':
         raise RuntimeError(
             """Django can't perform a SSL redirect while maintaining POST data.
             Please structure your views so that redirects only occur during GETs.""")
     
     protocol = secure and "https" or "http"
     
     newurl = "%s://%s%s" % (protocol, get_host(request), request.get_full_path())
     return HttpResponsePermanentRedirect(newurl)
예제 #36
0
 def _redirect(self, request, secure):
     protocol = secure and "https" or "http"
     url = "%s://%s%s" % (protocol, get_host(request), request.get_full_path())
     if settings.DEBUG and request.method == 'POST':
         raise RuntimeError(
             """Django can't perform a redirect while maintaining POST data.
             Please structure your views so that redirects only occur during GETs.""")
     if request.is_ajax():
         return HttpResponseAjax([commands.redirect(url)])
     else:
         return HttpResponseRedirect(url)
예제 #37
0
파일: ssl.py 프로젝트: alvaromartin/baph
    def redirect(self, request, secure):
        protocol = 'https' if secure else 'http'
        new_url = '%s://%s%s' % (protocol, get_host(request),
                                 request.get_full_path())

        if settings.DEBUG and request.method == 'POST':
            raise RuntimeError('''\
Django can't perform a SSL redirect while maintaining POST data.
Please structure your views so that redirects only occur during GETs.''')

        return HttpResponseRedirect(new_url)
예제 #38
0
    def redirect(self, request, secure):
        protocol = 'https' if secure else 'http'
        new_url = '%s://%s%s' % (protocol, get_host(request),
                                 request.get_full_path())

        if settings.DEBUG and request.method == 'POST':
            raise RuntimeError('''\
Django can't perform a SSL redirect while maintaining POST data.
Please structure your views so that redirects only occur during GETs.''')

        return HttpResponseRedirect(new_url)
예제 #39
0
파일: views.py 프로젝트: keokilee/makahiki
def _service_url(request, redirect_to=None):
    """Generates application service URL for CAS"""

    protocol = ('http://', 'https://')[request.is_secure()]
    host = get_host(request)
    service = protocol + host + request.path
    if redirect_to:
        if '?' in service:
            service += '&'
        else:
            service += '?'
        service += urlencode({REDIRECT_FIELD_NAME: redirect_to})
    return service
예제 #40
0
 def process_request(self, request):
     if settings.HOSTER:
         system_secure = request.session.get('SYSTEM_S', False)
         path = request.get_full_path()
         path_first = path.split('/')[1]
         reg = re.compile(ur'(media)|(static)|(ajax)')
         search = reg.search(path_first)
         if not system_secure and not request.method == 'POST' and not search:
             newurl = u'https://%s%s' % (get_host(request),
                                         request.get_full_path())
             request.session['SYSTEM_S'] = True
             return HttpResponsePermanentRedirect(newurl)
         else:
             request.session['SYSTEM_S'] = False
예제 #41
0
def details(request,
            id,
            template_name="photos/details.html",
            group_slug=None,
            bridge=None):
    """
    show the photo details
    """

    if bridge:
        try:
            group = bridge.get_group(group_slug)
        except ObjectDoesNotExist:
            raise Http404
    else:
        group = None

    photos = Image.objects.all()

    if group:
        photos = group.content_objects(photos, join="pool")
    else:
        photos = photos.filter(pool__object_id=None)

    photo = get_object_or_404(photos, id=id)

    # @@@: test
    if not photo.is_public and request.user != photo.member:
        raise Http404

    photo_url = photo.get_display_url()

    title = photo.title
    host = "http://%s" % get_host(request)

    if photo.member == request.user:
        is_me = True
    else:
        is_me = False

    return render_to_response(template_name, {
        "group": group,
        "host": host,
        "photo": photo,
        "photo_url": photo_url,
        "is_me": is_me,
    },
                              context_instance=RequestContext(request))
예제 #42
0
def save_snapshot(http_request, image, type):
    """
    Saves an image to the static image dir.

    @param image: A L{pyamf.amf3.ByteArray} instance
    """
    fp = tempfile.mkstemp(dir=gateway.images_root,
                          prefix='snapshot_',
                          suffix='.' + type)

    fp = open(fp[1], 'wb+')
    fp.write(image.getvalue())
    fp.close()

    url = base_url % get_host(http_request)
    name = fp.name[len(gateway.images_root) + 1:]

    return {'url': url + name, 'name': name}
예제 #43
0
    def _redirect(self, request, secure):
        if settings.DEBUG and request.method == 'POST':
            raise RuntimeError(
                """Django can't perform a SSL redirect while maintaining POST data.
Please structure your views so that redirects only occur during GETs.""")

        protocol = secure and "https" or "http"
        host = "%s://%s" % (protocol, get_host(request))
        # In certain proxying situations, we need to strip out the 443 port
        # in order to prevent inifinite redirects
        if not secure:
            host = host.replace(':443', '')
        if secure and SSLPORT:
            host = "%s:%s" % (host, SSLPORT)

        newurl = "%s%s" % (host, request.get_full_path())

        return HttpResponseRedirect(newurl)
예제 #44
0
파일: views.py 프로젝트: kevinr/750book-web
def details(request, id, template_name="photos/details.html"):
    """
    show the photo details
    """
    
    group, bridge = group_and_bridge(request)
    
    photos = Image.objects.all()
    
    if group:
        photos = group.content_objects(photos, join="pool", gfk_field="content_object")
    else:
        photos = photos.filter(pool__object_id=None)
    
    photo = get_object_or_404(photos, id=id)
    
    # @@@: test
    if not photo.is_public and request.user != photo.member:
        raise Http404
    
    photo_url = photo.get_display_url()
    
    title = photo.title
    host = "http://%s" % get_host(request)
    
    if photo.member == request.user:
        is_me = True
    else:
        is_me = False
    
    ctx = group_context(group, bridge)
    ctx.update({
        "host": host,
        "photo": photo,
        "photo_url": photo_url,
        "is_me": is_me,
    })
    
    return render_to_response(template_name, RequestContext(request, ctx))
예제 #45
0
    def process_request(self, request):
        """
        Check for denied User-Agents and rewrite the URL based on
        settings.APPEND_SLASH and settings.PREPEND_WWW
        """

        # Check for denied User-Agents
        if request.META.has_key('HTTP_USER_AGENT'):
            for user_agent_regex in settings.DISALLOWED_USER_AGENTS:
                if user_agent_regex.search(request.META['HTTP_USER_AGENT']):
                    return http.HttpResponseForbidden('<h1>Forbidden</h1>')

        # Check for a redirect based on settings.APPEND_SLASH and settings.PREPEND_WWW
        host = http.get_host(request)
        old_url = [host, request.path]
        new_url = old_url[:]
        if settings.PREPEND_WWW and old_url[0] and not old_url[0].startswith(
                'www.'):
            new_url[0] = 'www.' + old_url[0]
        # Append a slash if append_slash is set and the URL doesn't have a
        # trailing slash or a file extension.
        if settings.APPEND_SLASH and (old_url[1][-1] != '/') and (
                '.' not in old_url[1].split('/')[-1]):
            new_url[1] = new_url[1] + '/'
            if settings.DEBUG and request.method == 'POST':
                raise RuntimeError, "You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to %s%s (note the trailing slash), or set APPEND_SLASH=False in your Django settings." % (
                    new_url[0], new_url[1])
        if new_url != old_url:
            # Redirect
            if new_url[0]:
                newurl = "%s://%s%s" % (request.is_secure() and 'https'
                                        or 'http', new_url[0], new_url[1])
            else:
                newurl = new_url[1]
            if request.GET:
                newurl += '?' + request.GET.urlencode()
            return http.HttpResponsePermanentRedirect(newurl)

        return None
예제 #46
0
def get_snapshots(http_request):
    """
    Gets a list of snapshots in the images dir.

    @return: list with 3 elements: URL of image folder, allowed filetypes and
        the L{ArrayCollection} of snapshots
    """
    url = base_url % get_host(http_request)
    extensions = file_types.split(',')
    l = []

    for type in extensions:
        location = os.path.join(gateway.images_root, '*.' + type.strip())
        for img in glob.glob(location):
            name = img[len(gateway.images_root) + 1:]
            obj = {'name': name}

            l.append(obj)

    l.reverse()

    return [url, extensions, ArrayCollection(l[:max_result])]
예제 #47
0
def templatepage(request, url, template_dir='templatepages/', extra_context={}, context_processors=None):

    # If Django's APPEND_SLASH setting is enabled, and the URL does not end
    # with a slash or a file extension, Django will redirect to the URL with a
    # slash appended

    if template_dir and template_dir[-1] != '/':
        template_dir += '/'

    host = get_host(request).strip().lower()

    if host:
        try:
            template_host_dir = HOST_RE.match(host).groups()[0]
        except AttributeError:
            response = HttpResponse()
            response.status_code = 400
            response.write('[%s]' % get_host(request))
            return response
    else:
        template_host_dir = 'nohost'

    try:
        if settings.TEMPLATEPAGES_MULTISITE:
            prefix_list = (template_host_dir + '/', 'default/')
        else:
            prefix_list = ('',)
    except AttributeError:
        prefix_list = ('',)

    # Discard any bad segments in URL ("//", "/./". or "/../")
    clean_url = '/'.join([x for x in url.strip().split('/') if x not in ('','.','..')])

    for prefix in (prefix_list):
        try:
            t = loader.get_template(template_dir + prefix + clean_url)
            mimetype, encoding = guess_type(clean_url)
            break
        except TemplateDoesNotExist:
            pass
        try:
            t = loader.get_template(template_dir + prefix + clean_url + '/index.html')
            mimetype, encoding = guess_type('index.html')
            break
        except TemplateDoesNotExist:
            pass
    else:
        raise Http404

    context = RequestContext(request, {'url': url, 'host': host}, context_processors)
    if extra_context:
        for key, value in extra_context.items():
            if callable(value):
                context[key] = value()
            else:
                context[key] = value

    response = HttpResponse(t.render(context))
    response['Content-Type'] = mimetype or 'application/octet-stream'
    if encoding:
        response['Content-Encoding'] = encoding

    return response
예제 #48
0
    def _redirect(self, request, secure):
        protocol = secure and "https" or "http"
        newurl = "%s://%s%s" % (protocol, get_host(request),
                                request.get_full_path())

        return HttpResponsePermanentRedirect(newurl)
예제 #49
0
파일: views.py 프로젝트: exezaid/Dpress
def get_address(path, request):
    try:
        out = path.split(get_host(request), 1)[1]
    except AttributeError:
        return None
예제 #50
0
파일: views.py 프로젝트: cjs/bme
def details(request, id, template_name="photos/details.html"):
    """
    show the photo details
    """
    photo = get_object_or_404(Photo, id=id)
    # @@@: test
    if not photo.is_public and request.user != photo.member:
        raise Http404
    photo_url = photo.display.url
    
    tribes = []
    projects = []
    
    # Build a list of tribes and the photos from the pool
    for tribe in Tribe.objects.filter(members=request.user):
        phototribe = Tribe.objects.get(pk=tribe.id)
        if phototribe.photos.filter(photo=photo).count():
            tribes.append({
                "name": tribe.name,
                "slug": tribe.slug,
                "id": tribe.id,
                "has_photo": True,
            })
        else:
            tribes.append({
                "name": tribe.name,
                "slug": tribe.slug,
                "id": tribe.id,
                "has_photo": False,
            })

    # Build a list of projects and the photos from the pool
    for project in Project.objects.filter(members__user=request.user):
        photoproject = Project.objects.get(pk=project.id)
        if photoproject.photos.filter(photo=photo).count():
            projects.append({
                "name": project.name,
                "slug": project.slug,
                "id": project.id,
                "has_photo": True,
            })
        else:
            projects.append({
                "name": project.name,
                "slug": project.slug,
                "id": project.id,
                "has_photo": False,
            })

    title = photo.title
    host = "http://%s" % get_host(request)
    if photo.member == request.user:
        is_me = True
    else:
        is_me = False
    # TODO: check for authorized user and catch errors
    if is_me:
        if request.method == "POST" and request.POST["action"] == "add_to_project":
            projectid = request.POST["project"]
            myproject = Project.objects.get(pk=projectid)
            if not myproject.photos.filter(photo=photo).count():
                myproject.photos.create(photo=photo)
                request.user.message_set.create(message=_("Successfully add photo '%s' to project") % title)
            else:
                # TODO: this applies to pinax in general. dont use ugettext_lazy here. its usage is fragile.
                request.user.message_set.create(message=_("Did not add photo '%s' to project because it already exists.") % title)

            return HttpResponseRedirect(reverse('photo_details', args=(photo.id,)))
        
        if request.method == "POST":
            if request.POST["action"] == "addtotribe":
                tribeid = request.POST["tribe"]
                mytribe = Tribe.objects.get(pk=tribeid)
                if not mytribe.photos.filter(photo=photo).count():
                    mytribe.photos.create(photo=photo)
                    request.user.message_set.create(message=_("Successfully add photo '%s' to tribe") % title)
                else:
                    # TODO: this applies to pinax in general. dont use ugettext_lazy here. its usage is fragile.
                    request.user.message_set.create(message=_("Did not add photo '%s' to tribe because it already exists.") % title)

                return HttpResponseRedirect(reverse('photo_details', args=(photo.id,)))

            if request.POST["action"] == "removefromtribe":
                tribeid = request.POST["tribe"]
                mytribe = Tribe.objects.get(pk=tribeid)
                if mytribe.photos.filter(photo=photo).count():
                    mytribe.photos.filter(photo=photo).delete()
                    request.user.message_set.create(message=_("Successfully removed photo '%s' from tribe") % title)
                else:
                    # TODO: this applies to pinax in general. dont use ugettext_lazy here. its usage is fragile.
                    request.user.message_set.create(message=_("Did not remove photo '%s' from tribe.") % title)

                return HttpResponseRedirect(reverse('photo_details', args=(photo.id,)))

            if request.POST["action"] == "addtoproject":
                projectid = request.POST["project"]
                myproject = Project.objects.get(pk=projectid)
                if not myproject.photos.filter(photo=photo).count():
                    myproject.photos.create(photo=photo)
                    request.user.message_set.create(message=_("Successfully add photo '%s' to project") % title)
                else:
                    # TODO: this applies to pinax in general. dont use ugettext_lazy here. its usage is fragile.
                    request.user.message_set.create(message=_("Did not add photo '%s' to project because it already exists.") % title)

                return HttpResponseRedirect(reverse('photo_details', args=(photo.id,)))

            if request.POST["action"] == "removefromproject":
                projectid = request.POST["project"]
                myproject = Project.objects.get(pk=projectid)
                if myproject.photos.filter(photo=photo).count():
                    myproject.photos.filter(photo=photo).delete()
                    request.user.message_set.create(message=_("Successfully removed photo '%s' from project") % title)
                else:
                    # TODO: this applies to pinax in general. dont use ugettext_lazy here. its usage is fragile.
                    request.user.message_set.create(message=_("Did not remove photo '%s' from project.") % title)

                return HttpResponseRedirect(reverse('photo_details', args=(photo.id,)))

    return render_to_response(template_name, {
        "host": host, 
        "photo": photo,
        "photo_url": photo_url,
        "is_me": is_me,
        "projects": projects,
        "tribes": tribes,
    }, context_instance=RequestContext(request))
예제 #51
0
 def _add_protocol(self, request, protocol):
     return "%s://%s%s" % (protocol, get_host(request), request.get_full_path())