Exemplo n.º 1
0
    def __call__(self, request):
        if request.path == '/tutorials/':
            return HttpResponsePermanentRedirect('/courses/')

        if request.path == '/category/django-blog-tutorial/':
            return HttpResponsePermanentRedirect(
                '/courses/django-blog-tutorial/')

        if request.path.startswith('/post'):
            frags = request.path.split('/')
            post_id = frags[2]

            if post_id == '2':
                return HttpResponsePermanentRedirect(
                    '/courses/django-blog-tutorial/')

            with open(
                    os.path.join(str(environ.Path(__file__) - 1),
                                 'post_material_id_mapping.json'), 'r') as f:
                post_material_id_mapping = json.load(f)
            if post_id in post_material_id_mapping:
                material_id = post_material_id_mapping[post_id]
                material = Material.objects.get(pk=material_id)

                return redirect(material, permanent=True)

        response = self.get_response(request)
        return response
Exemplo n.º 2
0
 def fotoforum_clanek(self, request, response):
     comment_id = request.GET.get('clanek')
     if comment_id:
         naction = request.GET.get('NACTION')
         if naction is None:
             path = reverse('comment-detail', args=(comment_id, ))
             response = HttpResponsePermanentRedirect(path)
         elif naction == 'thread':
             path = reverse('comment-thread', args=(comment_id, ))
             response = HttpResponsePermanentRedirect(path)
     return response
Exemplo n.º 3
0
def login(request):
    if (request.method == 'POST'):
        email = request.POST.get('email')
        password = request.POST.get('password')
        try:
            user = User.objects.get(email=email, password=password)
            request.session['user_email'] = user.email
            request.session['user_password'] = user.password
            return HttpResponsePermanentRedirect(
                '/accounts/' + user.email[:user.email.find('@')])
        except:
            return HttpResponsePermanentRedirect('/')
    elif (request.method == 'GET'):
        return render(request, 'login.html')
Exemplo n.º 4
0
 def fotoforum_archiv(self, request, response):
     q = request.GET.get('hledej')
     if request.GET.get('NACTION') == 'find' and q:
         path = reverse('comment-archive', kwargs={'action': 'archive'})
         qs = urlencode({'q': q}, doseq=True)
         response = HttpResponsePermanentRedirect('{}?{}'.format(path, qs))
     return response
Exemplo n.º 5
0
    def _redirect2_https(self, request, secure):
        newurl = "https://{}{}".format(request.get_host(), request.get_full_path())
        if request.method == 'POST':
            raise GenericServiceError(u"Can not redirect to https in POST method. Make call with https")

        logger.debug("redirecting request to %s", newurl)
        return HttpResponsePermanentRedirect(newurl)
Exemplo n.º 6
0
 def fotogalerie_fotky(self, request, response):
     month = request.GET.get('mesic')
     section = request.GET.get('tema')
     if not month and not section:
         path = reverse('photos-listing-time')
         response = HttpResponsePermanentRedirect(path)
     elif month and not section:
         path = reverse('photos-listing-month', kwargs={'month': month})
         response = HttpResponsePermanentRedirect(path)
     elif not month and section:
         if section == '1':
             path = reverse('photos-listing-no-section')
         else:
             path = reverse('photos-listing-section',
                            kwargs={'section': section})
         response = HttpResponsePermanentRedirect(path)
     return response
Exemplo n.º 7
0
    def get(self, request, *args, **kwargs):
        self.object = obj = self.get_object()
        correct_url = reverse('parties:detail', args=[obj.slug, obj.pk])
        if request.path != correct_url:
            return HttpResponsePermanentRedirect(correct_url)

        context = self.get_context_data(object=obj)
        return self.render_to_response(context)
Exemplo n.º 8
0
 def get(self, request, *args, **kwargs):
     if request.get_host() != get_anchor_domain():
         return HttpResponsePermanentRedirect(
             redirect_to=urljoin(
                 get_anchor_domain(), request.get_full_path()
             )
         )
     return super().get(request, *args, **kwargs)
Exemplo n.º 9
0
Arquivo: views.py Projeto: yolfer/cs50
def book(request, flight_id):
    if request.method == "POST":
        # TODO error checking
        flight = Flight.objects.get(pk=flight_id)
        passenger = Passenger.objects.get(pk=int(request.POST["passenger"]))
        passenger.flights.add(flight)
        return HttpResponsePermanentRedirect(
            reverse("flight", args=(flight.id, )))
Exemplo n.º 10
0
 def __call__(self, request):
     response = self.get_response(request)
     if response.status_code == 200 and request.method == 'GET' and request.resolver_match and request.resolver_match.view_name in HTTPS_VIEW_NAMES and request.scheme == 'http' and not settings.DEBUG:
         uri = request.build_absolute_uri(request.get_full_path())
         if uri.startswith('http://'):
             uri = 'https://' + uri[7:]
             return HttpResponsePermanentRedirect(uri)
     return response
Exemplo n.º 11
0
    def process_request(self, request):
        host = request.get_host()

        # redirect www.foo.com to foo.com?
        if settings.STRIP_WWW and host.startswith("www."):
            redirect_url = '%s://%s%s' % (request.scheme, host[4:],
                                          request.get_full_path())
            return HttpResponsePermanentRedirect(redirect_url)
Exemplo n.º 12
0
 def fotogalerie_komentare(self, request, response):
     username = request.GET.get('autor')
     if username:
         path = reverse('photos-listing-comments-user',
                        kwargs={'user': username})
     else:
         path = reverse('photos-listing-comments')
     return HttpResponsePermanentRedirect(path)
Exemplo n.º 13
0
def single_composer(request, pComposerSlug):
    """
    Show details of a single composer
    """
    try:
        lPerson = Person.objects.filter(old_composer_slug=pComposerSlug)[0]
    except IndexError:
        raise Http404
    
    return HttpResponsePermanentRedirect("/people/%s/" % lPerson.slug) 
Exemplo n.º 14
0
def single_adjudicator(request, pAdjudicatorSlug):
    """
    Show details for a single adjudicator
    """
    try:
        lPerson = Person.objects.filter(
            old_adjudicator_slug=pAdjudicatorSlug)[0]
    except IndexError:
        raise Http404

    return HttpResponsePermanentRedirect("/people/%s/" % lPerson.slug)
Exemplo n.º 15
0
 def fotoforum(self, request, response):
     naction = request.GET.get('NACTION')
     if not naction or naction == 'clanky':
         path = reverse('comment-time')
         response = HttpResponsePermanentRedirect(path)
     elif naction == 'temata':
         path = reverse('comment-themes')
         response = HttpResponsePermanentRedirect(path)
     elif naction == 'den':
         day = request.GET.get('den')
         if not day:
             day = timezone.now().strftime('%Y-%m-%d')
         path = reverse('comment-date', kwargs={'date': day})
         response = HttpResponsePermanentRedirect(path)
     elif naction == 'author':
         username = request.GET.get('author')
         if username:
             path = reverse('comment-user', kwargs={'user': username})
             response = HttpResponsePermanentRedirect(path)
     return response
Exemplo n.º 16
0
    def redirect(self, url=None, message=None, *args, **kwargs):
        url = self.get_redirect_url(url, *args, **kwargs)
        if url:
            if message:
                self.set_message(message)

            if self.permanent:
                return HttpResponsePermanentRedirect(url)
            else:
                return HttpResponseRedirect(url)
        else:
            return HttpResponseGone()
Exemplo n.º 17
0
def angular_reverse(request, *args, **kwargs):
    url_name = request.GET.get('djng_url_name')
    url_args = request.GET.getlist('djng_url_args', None)
    url_kwargs = {}

    prefix = 'djng_url_kwarg_'
    for param in request.GET:
        if param.startswith(prefix):
            url_kwargs[param[len(prefix):]] = request.GET[param]

    url = reverse(url_name, args=url_args, kwargs=url_kwargs)
    return HttpResponsePermanentRedirect(url)
Exemplo n.º 18
0
 def get(self, request, *args, **kwargs):
     try:
         return super().get(request, *args, **kwargs)
     except Http404:
         # if not found, check for a match on a past PGPID
         doc = Document.objects.filter(
             old_pgpids__contains=[self.kwargs["pk"]]).first()
         # if found, redirect to the correct url for this view
         if doc:
             self.kwargs["pk"] = doc.pk
             return HttpResponsePermanentRedirect(self.get_absolute_url())
         # otherwise, continue raising the 404
         raise
Exemplo n.º 19
0
def _show_single_conductor_page(request,
                                pConductorSlug,
                                pContestFilterSlug=None,
                                pGroupFilterSlug=None,
                                pFilterTagSlug=None):
    """
    Show single conductor page
    """
    try:
        lPerson = Person.objects.filter(old_conductor_slug=pConductorSlug)[0]
    except IndexError:
        raise Http404

    return HttpResponsePermanentRedirect("/people/%s/" % lPerson.slug)
    def process_request(self, request):
        """
        Redirects all unslashed paths that match the SLASHED_PATHS setting to their slashed version.
        Redirects all slashed paths that don't match the SLASHED_PATHS setting to their slashless version.
        """
        # For some dumb reason, str.startswith() ONLY accepts tuples of strings.
        # Thus, we cast to tuple to allow our users to use any sequence type for SLASHED_PATHS.
        slashed_paths = tuple(getattr(settings, 'SLASHED_PATHS', []))

        if request.path.startswith(
                slashed_paths) and not request.path.endswith('/'):
            # Redirect to slashed versions.
            url = request.path + '/'
            if request.GET:
                url += '?{}'.format(urlencode(request.GET, True))
            return HttpResponsePermanentRedirect(url)
        elif (not request.path.startswith(slashed_paths)
              and request.path.endswith('/') and not request.path == '/'):
            # Redirect to unslashed versions.
            url = request.path[:-1]
            if request.GET:
                url += '?{}'.format(urlencode(request.GET, True))
            return HttpResponsePermanentRedirect(url)
Exemplo n.º 21
0
def create_lot(request):
    if request.user.profile.is_manager() or request.user.profile.is_supervisor(
    ):
        params = request.POST
        lot_name = params['lotName']
        lot_address = params['lotAddress']

        new_lot = ParkingLot(name=lot_name,
                             address=lot_address,
                             owner=request.user)
        new_lot.save()

        return HttpResponsePermanentRedirect(f"/assign_areas?lot={new_lot.pk}")
    return redirect("genie:index")
Exemplo n.º 22
0
    def dispatch(self, request, *args, **kwargs):
        """
        Base class view for all HTML views.

        A fair bit is happening here. The WebPageWrapperView parses a url request, like '/shows', 
        calculates the API endpoint that web request corresponds to, e.g. 'shows.json', issues a GET 
        to that url, loads the received JSON and passes that data to the template.

        It also appends a slug to the resulting url if needed, for SEO purposes.
        """
        try:
            if 'favicon.ico' in self.request.path:
                return HttpResponse(200)
            resolver_match = resolve(self.get_api_url(*args, **kwargs),
                                     self.url_namespace)
        except Resolver404:
            raise Http404

        resolved_url_name = resolver_match.url_name

        if resolved_url_name in REDIRECT_NEEDED_URL_PATTERNS and not kwargs.get(
                'page_slug'):
            redirect_url = get_slug_redirect(request.path)
            if redirect_url:
                return HttpResponsePermanentRedirect(
                    redirect_url)  # uses a 301 instead of 302 code

        response = resolver_match.func(request, *resolver_match.args,
                                       **resolver_match.kwargs)
        if response.status_code >= 400:
            return response

        # working solution
        if isinstance(response, TemplateResponse):
            response.render()

        self.page_data = json.loads(response.content.decode())
        for widget in self.page_data.get('widgets', []):
            template_name = "widgets/{}.html".format(widget['type'])
            try:
                get_template(template_name)
            except TemplateDoesNotExist:
                pass
            else:
                widget['template_name'] = template_name

        return super(WebPageWrapperView,
                     self).dispatch(request, *args, **kwargs)
Exemplo n.º 23
0
 def to_djangoresponse(self):
     """django用のレスポンス.
     """
     content_type = self.__headers.get('content-type', 'text/plain')
     self.set_header('content-length', str(len(self.__body)))
     django_response = DjangoHttpResponse(self.__body, content_type=content_type, status=self.status)
     for k, v in self.__headers.items():
         django_response[k] = v
     if self.status == 301:
         django_response = HttpResponsePermanentRedirect(django_response.get('location'))
     elif self.status == 302:
         django_response = HttpResponseRedirect(django_response.get('location'))
     for k, arr in self.__cookies.items():
         v, expires, domain = arr
         django_response.set_cookie(k, v, expires=expires, domain=domain)
     return django_response
Exemplo n.º 24
0
    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        host = request.get_host()

        # redirect www.foo.com to foo.com?
        if settings.STRIP_WWW and host.startswith("www."):
            redirect_url = '%s://%s%s' % (request.scheme, host[4:],
                                          request.get_full_path())
            return HttpResponsePermanentRedirect(redirect_url)

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.

        return response
Exemplo n.º 25
0
    def post(self, request):
        if request.FILES:
            try:
                code = ''.join(random.sample(string.digits, 10))
                for each in request.FILES.getlist('file'):
                    NepDiskFile.objects.create(
                        file=each,
                        name_display=each.name,
                        code=code,
                        owner=request.user,
                        upload_ip=request.META['REMOTE_ADDR'])
                return HttpResponsePermanentRedirect("/disk/s/" + code)

            except Exception as any_exec:
                print(repr(any_exec))
                return HttpResponseRedirect("/disk/home/")
        else:
            return HttpResponse("not file")
Exemplo n.º 26
0
def node(request, node_id=None, allowed_hidden_classes=None):
    """
    Gets node by ID or by request path

    Optionally pass a list of models which are allowed to be shown in spite of being set up as hidden
    """
    language = get_language()
    if not node_id:
        url = request.path_info[1:]

        q = Q(url_alias__exact=url)

        if url.endswith("/"):
            q |= Q(url_alias__exact=url.strip("/"))
        else:
            q |= Q(url_alias__exact=url + "/")

        node = get_object_or_404(Node, q, language=language, published=True)

        if node.url_alias != url:
            args = request.META.get('QUERY_STRING', '')
            if args:
                node.url_alias += "?%s" % args
            domain = settings.LANGUAGE_SETTINGS[language]["redirect_to"]
            return HttpResponsePermanentRedirect(domain + "/" + node.url_alias)
    else:
        node = get_object_or_404(Node, id=node_id, language=language)
    node = node.as_leaf_class()
    if node.hide and (allowed_hidden_classes is None or type(node) not in allowed_hidden_classes):
        raise Http404()
    if not node.public_access:
        if not request.user.is_authenticated():
            return redirect('auth_login')
        if not node.has_access(request.user):
            return HttpResponseForbidden()
    if hasattr(node, "check_access") and not node.check_access(request.user):
        return HttpResponseForbidden()
    if request.is_ajax():
        return HttpResponse(node.render())

    context = {'node': node}
    context.update(node.get_context_values())
    return render_to_response(node.get_template_name(request), context,
                              context_instance=RequestContext(request))
Exemplo n.º 27
0
def delete_area(request):
    if request.user.profile.is_manager() or request.user.profile.is_supervisor(
    ):
        params = request.GET

        if "area" in params:
            area_id = int(unquote(params["area"]))
            area = LotArea.objects.get(pk=area_id)
            if request.user == area.parkingLot.owner:
                reservations = Reservation.objects.filter(lotArea=area).all()
                if not reservations:
                    area.delete()
                else:
                    messages.error(
                        request,
                        f"Cannot delete area {area.areaIdentifier}. Reservations for this area have already been made.",
                        "error")
                return HttpResponsePermanentRedirect(
                    f"/assign_areas?lot={area.parkingLot.pk}")
    return redirect("genie:index")
    def process_request(self, request):
        """
        Set request.site to the Site object responsible for handling this request. Wagtail's version of this
        middleware only looks at the Sites' hostnames. Ours must also consider the Sites' lists of aliases.

        This middleware also denies access to users who have valid accounts, but aren't members of the current Site.
        """
        try:
            match_type, request.site = match_site_to_request(request)
        except Site.DoesNotExist:
            try:
                hostname = request.META['HTTP_HOST'].split(':')[0]
            except KeyError:
                hostname = None
            logger.warning('site.does_not_exist', hostname=hostname)
            request.site = None
        except MissingHostException:
            # If no hostname was specified, we return a 400 error. This should really only happen during tests.
            return HttpResponseBadRequest()
        else:
            # When a user visits an admin page via an alias or a non-https URL, we need to redirect them to the https
            # version of the Site's canonical domain (so the SSL cert will work).
            if request.path.startswith('/admin/') and (
                    match_type == 'alias' or not request.is_secure()):
                url = 'https://{}{}'.format(request.site.hostname,
                                            request.path)
                if request.GET:
                    url += '?{}'.format(urlencode(request.GET, True))
                return HttpResponsePermanentRedirect(url)

            # Non-superusers are not allowed to be logged in to Sites they aren't members of.
            # This will NOT log them out of any site besides request.site.
            if (not request.user.is_anonymous and not request.user.is_superuser
                    and
                    not user_is_member_of_site(request.user, request.site)):
                messages.error(request, 'Invalid credentials.')
                logger.warning('auth.site.browse.user_not_member',
                               username=request.user.username,
                               site=request.site.hostname)
                logout(request)
Exemplo n.º 29
0
def signup(request):
    if (request.method == 'POST'):
        email = request.POST.get('email')
        password = request.POST.get('password')
        #print "{0} - {1}".format(email, password)

        user = User(email=email, password=password)
        user.save()

        res = "A user saved to db\n"
        res += "Email: {} \n".format(user.email)
        res += "Password: {} \n".format(user.password)
        res += "Date: {} \n".format(user.date_modified)

        print res

        request.session['user_email'] = user.email
        request.session['user_password'] = user.password
        return HttpResponsePermanentRedirect('/accounts/' +
                                             user.email[:user.email.find('@')])
    elif (request.method == 'GET'):
        return render(request, 'signup.html')
Exemplo n.º 30
0
def update_area(request):
    if request.user.profile.is_manager() or request.user.profile.is_supervisor(
    ):
        params = request.POST
        if "area" in request.GET:
            area_pk = int(unquote(request.GET["area"]))
            area = LotArea.objects.get(pk=area_pk)
            if request.user == area.parkingLot.owner:
                area_id = unquote(params["area"])
                capacity = unquote(params["capacity"])
                type = unquote(params["type"])
                price = float(unquote(params["price"]))

                area.areaIdentifier = area_id
                area.capacity = capacity
                area.type = type
                area.price = price

                area.save()
                return HttpResponsePermanentRedirect(
                    f"/assign_areas?lot={area.parkingLot.pk}")
    return redirect("genie:index")