def process_request(self, request): static_redirect = StaticRedirect.objects.get_for_request(request) if static_redirect: full_domain = '{}://{}'.format( request.scheme, Site.objects.get(id=settings.SITE_ID).domain) return http.HttpResponsePermanentRedirect( static_redirect.get_outbound_url(full_domain)) path = request.path_info path_with_queries = request.get_full_path() queries = (Q(old_path__iexact=path) | Q(old_path__iexact=path_with_queries)) if settings.APPEND_SLASH and path.endswith('/'): path_with_queries_no_slash = path[:-1] + path_with_queries[len(path ):] queries |= (Q(old_path__iexact=path[:-1]) | Q(old_path__iexact=path_with_queries_no_slash)) try: r = Redirect.objects.filter( queries, site__id__exact=settings.SITE_ID).distinct().get() except Redirect.DoesNotExist: return new_path = r.safe_translation_getter('new_path', any_language=True) if new_path in (None, ''): return http.HttpResponseGone() return http.HttpResponsePermanentRedirect(new_path)
def process_response(request, response): if response.status_code != 404: return response full_path = request.get_full_path() redirect = None try: redirect = Redirect.objects.get(old_path=full_path) except Redirect.DoesNotExist: pass if settings.APPEND_SLASH and not request.path.endswith('/'): # Try appending a trailing slash. path_len = len(request.path) full_path = full_path[:path_len] + '/' + full_path[path_len:] try: redirect = Redirect.objects.get(old_path=full_path) except Redirect.DoesNotExist: pass if redirect is None: return response if redirect.new_path == '': return http.HttpResponseGone() redirect.last_usage = now() redirect.save() if redirect.permanent: return http.HttpResponsePermanentRedirect(redirect.new_path) else: return http.HttpResponseRedirect(redirect.new_path)
def process_exception(self, request, exception): if isinstance(exception, http.Http404): # First try the whole path. path = request.get_full_path() r = get_redirect(path) # It could be that we need to try without a trailing slash. if r is None and settings.APPEND_SLASH: r = get_redirect(remove_slash(path)) # It could be that the redirect is defined without a query string. if r is None and path.count('?'): r = get_redirect(remove_query(path)) # It could be that we need to try without query string and without a trailing slash. if r is None and path.count('?') and settings.APPEND_SLASH: r = get_redirect(remove_slash(remove_query(path))) if r is not None: if r.page: if r.response_code == '302': return http.HttpResponseRedirect(r.page.get_absolute_url()) else: return http.HttpResponsePermanentRedirect(r.page.get_absolute_url()) if r.new_path == '': return http.HttpResponseGone() if r.response_code == '302': return http.HttpResponseRedirect(r.new_path) else: return http.HttpResponsePermanentRedirect(r.new_path)
def process_response(self, request, response): if response.status_code != 404: return response # No need to check for a redirect for non-404 responses. path = request.get_full_path() cache_key = redirect_cache_key(path) new_path = cache.get(cache_key, None) if new_path is None: try: r = Redirect.objects.get(site__id__exact=settings.SITE_ID, old_path=path) except Redirect.DoesNotExist: r = None if r is None and settings.APPEND_SLASH: # Try removing the trailing slash. try: r = Redirect.objects.get(site__id__exact=settings.SITE_ID, old_path=path[:path.rfind('/')] + path[path.rfind('/') + 1:]) except Redirect.DoesNotExist: pass if r is not None: new_path = r.new_path cache.set(cache_key, new_path, CACHE_REDIRECT_TIMEOUT) else: cache.set(cache_key, DNE, CACHE_REDIRECT_TIMEOUT) if new_path is not None: if new_path == '': return http.HttpResponseGone() if new_path != DNE: return http.HttpResponsePermanentRedirect(new_path) # No redirect was found. Return the response. return response
def process_exception(self, request, exception): if isinstance(exception, http.Http404): path = request.get_full_path() try: r = CMSRedirect.objects.get(site__id__exact=settings.SITE_ID, old_path=path) except CMSRedirect.DoesNotExist: r = None if r is None and settings.APPEND_SLASH: # Try removing the trailing slash. try: r = CMSRedirect.objects.get( site__id__exact=settings.SITE_ID, old_path=path[:path.rfind('/')] + path[path.rfind('/') + 1:]) except CMSRedirect.DoesNotExist: pass if r is not None: if r.page: if r.response_code == '302': return http.HttpResponseRedirect( r.page.get_absolute_url()) else: return http.HttpResponsePermanentRedirect( r.page.get_absolute_url()) if r.new_path == '': return http.HttpResponseGone() if r.response_code == '302': return http.HttpResponseRedirect(r.new_path) else: return http.HttpResponsePermanentRedirect(r.new_path)
def process_response(self, request, response): if response.status_code != 404: return response # No need to check for a redirect for non-404 responses. full_path = request.get_full_path() current_site = get_current_site(request) r = None try: r = Redirect.objects.get(site=current_site, old_path=full_path) except Redirect.DoesNotExist: pass if settings.APPEND_SLASH and not request.path.endswith('/'): # Try appending a trailing slash. path_len = len(request.path) full_path = full_path[:path_len] + '/' + full_path[path_len:] try: r = Redirect.objects.get(site=current_site, old_path=full_path) except Redirect.DoesNotExist: pass if r is not None: if r.new_path == '': return http.HttpResponseGone() return http.HttpResponsePermanentRedirect(r.new_path) # No redirect was found. Return the response. return response
def process_response(self, request, response): if response.status_code == 500: # Possible Database issue. Better let it through, # as transaction may have been aborted. return response full_path = request.get_full_path() current_site = get_current_site(request) r = None try: r = Redirect.objects.get(site=current_site, old_path=full_path) except Redirect.DoesNotExist: try: r = Redirect.objects.get(universal=True, old_path=full_path) except Redirect.DoesNotExist: pass if settings.APPEND_SLASH and not request.path.endswith('/'): # Try appending a trailing slash. path_len = len(request.path) full_path = full_path[:path_len] + '/' + full_path[path_len:] try: r = Redirect.objects.get(site=current_site, old_path=full_path) except Redirect.DoesNotExist: try: r = Redirect.objects.get(universal=True, old_path=full_path) except Redirect.DoesNotExist: pass if r is not None: if r.new_path == '': return http.HttpResponseGone() return http.HttpResponsePermanentRedirect(r.new_path) # No redirect was found. Return the response. return response
def get(self, request, *args, **kwargs): url = self.get_redirect_url(*args, **kwargs) if url: if self.permanent: return HttpSmartResponsePermanentRedirect(url) return HttpSmartResponseRedirect(url) return http.HttpResponseGone()
def process_response(self, request, response): """ Check if redirect_obj is needed. """ if response.status_code != 404: # No need to check for a redirect_obj for non-404 responses. return response path = request.get_full_path() try: redirect_obj = Redirect.objects.get(old_path=path, is_active=True) except Redirect.DoesNotExist: redirect_obj = None if redirect_obj is None and settings.APPEND_SLASH: # Try removing the trailing slash. try: old_path = path[:path.rfind('/')] + path[path.rfind('/') + 1:] redirect_obj = Redirect.objects.get(old_path=old_path, is_active=True) except Redirect.DoesNotExist: pass if redirect_obj is not None: if redirect_obj.new_path == '': return http.HttpResponseGone() return redirect(redirect_obj.new_path, permanent=redirect_obj.is_permanent) # No redirect_obj was found. Return the response. return response
def process_response(self, request, response): # we want to redirect regardless of 404 """if response.status_code != 404: return response # No need to check for a redirect for non-404 responses.""" path = request.get_full_path() try: r = Redirect.objects.get(site__id__exact=settings.SITE_ID, old_path=path) except Redirect.DoesNotExist: r = None if r is None and settings.APPEND_SLASH: # Try removing the trailing slash. try: r = Redirect.objects.get(site__id__exact=settings.SITE_ID, old_path=path[:path.rfind('/')] + path[path.rfind('/') + 1:]) except Redirect.DoesNotExist: pass if r is not None: if r.new_path == '': return http.HttpResponseGone() return http.HttpResponsePermanentRedirect(r.new_path) # No redirect was found. Return the response. return response
def person_detail_tab(request, sport, gsm_id, tab, tag='person', update=False, template_name='', extra_context=None): sport = get_sport_or_404(sport) if sport.slug in ('hockey', 'basketball', 'americanfootball'): return http.HttpResponseGone() gsm_entity_class = model_class_for_tag(tag) person, created = gsm_entity_class.objects.get_or_create(sport=sport, tag=tag, gsm_id=gsm_id) context = { 'sport': sport, 'language': get_language_from_request(request), 'person': person, 'tab': tab, } if sport.slug in 'tennis': t = gsm.get_tree(context['language'], sport, 'get_players', type='player', id=person.gsm_id, detailed='yes') else: t = gsm.get_tree(context['language'], sport, 'get_career', type='player', id=person.gsm_id, detailed='yes') person.element = t.getroot().getchildren()[1] if created: person.name = unicode(person) person.save() if tab == 'picks': context['bet_list_helper'] = BetListHelper(request, exclude_columns=['support'], **{tag: person}) template_name = [ 'gsm/%s/%s/%s.html' % (sport.slug, 'person', tab), 'gsm/%s/%s.html' % ('person', tab), ] context.update(extra_context or {}) return shortcuts.render_to_response( template_name, context, context_instance=template.RequestContext(request))
def get(self, request, *args, **kwargs): m = get_object_or_404(Recording, pk=kwargs['pk']) u = request.user p = get_or_create_person(request) rType = request.GET.get('json', False) audio_file = m.audio_file f = request.GET.get('format', 'aac') if f in 'wav': if m.audio_file_wav: audio_file = m.audio_file_wav else: if m.audio_file_aac: audio_file = m.audio_file_aac if p is not None: uuid = p.uuid else: uuid = 'None-Person-Object' key = '{0}:{1}:listen'.format(uuid, m.id) access = cache.get(key) # logger.debug(' CAN VIEW: {0} {1}'.format(key, access)) url = '' if (u.is_authenticated() and u.is_staff) or (p == m.person) or (access): try: url = audio_file.path url = audio_file.url except: try: url = self.get_redirect_url(filepath=audio_file.name) except: url = audio_file.url if url: if rType: return http.HttpResponse( json.dumps({'url': url}), content_type="application/json") if self.permanent: return http.HttpResponsePermanentRedirect(url) else: return http.HttpResponseRedirect(url) else: logger.warning('Gone: %s', self.request.path, extra={ 'status_code': 410, 'request': self.request }) return http.HttpResponseGone() else: if rType: return http.HttpResponse( json.dumps({'error': 'Access denied.'}), content_type="application/json") raise http.Http404
def server_moocng_error(request, exception): status_code = exception.http_status_code t = loader.select_template(('%s.html' % status_code, 'http_error.html')) return http.HttpResponseGone( t.render( RequestContext( request, { 'request_path': request.path, 'title': exception.error_name, 'message_exception': exception.message, 'status_code': status_code })))
def get(self, request, *args, **kwargs): url = self.get_redirect_url(*args, **kwargs) if url: if self.permanent: return http.HttpResponsePermanentRedirect(url) else: return http.HttpResponseRedirect(url) else: logger.warning( 'Gone: %s', request.path, extra={'status_code': 410, 'request': request} ) return http.HttpResponseGone()
def delete(self, request, msg_id): if not request.user.is_authenticated(): return http.HttpResponseForbidden() try: Message.objects.get(id=msg_id).unvote(request.user) except ObjectDoesNotExist: return http.HttpResponseGone() # 204 No Content # empty body, as per RFC2616. # object deleted return http.HttpResponse(status=204)
def process_response(self, request, response): if not settings.USE_I18N: return super(DjangoplicityRedirectFallbackMiddleware, self).process_response(request, response) if response.status_code != 404: return response # No need to check for a redirect for non-404 responses. full_path = request.get_full_path() current_site = get_current_site(request) r = None try: r = Redirect.objects.get(site=current_site, old_path=full_path) except Redirect.DoesNotExist: pass if not r: # Let's check if the current path is a local (translated) path # and whether we have a redirect for the original path lang, dummy_prefix, original_path = get_language_from_path( full_path) if full_path != original_path: try: r = Redirect.objects.get(site=current_site, old_path=original_path) # We update the Redirects' new_path with the prefix of the # current language to prevent another redirect round trip # later on but we don't save it r.new_path = get_path_for_language(lang, r.new_path) except Redirect.DoesNotExist: pass if settings.APPEND_SLASH and not request.path.endswith('/'): # Try appending a trailing slash. path_len = len(request.path) full_path = full_path[:path_len] + '/' + full_path[path_len:] try: r = Redirect.objects.get(site=current_site, old_path=full_path) except Redirect.DoesNotExist: pass if r is not None: if r.new_path == '': return http.HttpResponseGone() return http.HttpResponsePermanentRedirect(r.new_path) # No redirect was found. Return the response. return response
def process_exception(self, request, exception): if isinstance(exception, http.Http404): # First try the whole path. path = request.get_full_path() r = get_redirect(path) # Isolate the query string if path.count('?'): qs = path.split('?')[1] else: qs = None # It could be that we need to try without a trailing slash. if r is None and settings.APPEND_SLASH: r = get_redirect(remove_slash(path)) # It could be that the redirect is defined without a query string. if r is None and path.count('?'): r = get_redirect(remove_query(path)) # It could be that we need to try without query string and without a trailing slash. if r is None and path.count('?') and settings.APPEND_SLASH: r = get_redirect(remove_slash(remove_query(path))) if r is not None: if r.page: new_url = r.page.get_absolute_url() if qs: new_url = new_url + '?' + qs if r.response_code == '302': return http.HttpResponseRedirect(new_url) else: return http.HttpResponsePermanentRedirect(new_url) if r.new_path == '': return http.HttpResponseGone() if r.response_code == '302': new_url = r.new_path # Only append the querystring if the new path doesn't have it's own if qs and not r.new_path.count('?'): new_url = new_url + '?' + qs return http.HttpResponseRedirect(new_url) else: new_url = r.new_path # Only append the querystring if the new path doesn't have it's own if qs and not r.new_path.count('?'): new_url = new_url + '?' + qs return http.HttpResponsePermanentRedirect(new_url)
def signup(request, location, study_group_id): study_group = get_object_or_404(StudyGroup, pk=study_group_id) if not study_group.deleted_at is None: return http.HttpResponseGone() ## TODO if request.method == 'POST': form = ApplicationForm(request.POST, initial={'study_group': study_group}) if form.is_valid( ) and study_group.signup_open == True and study_group.draft == False: application = form.save(commit=False) if application.email and Application.objects.active().filter( email__iexact=application.email, study_group=study_group).exists(): old_application = Application.objects.active().filter( email__iexact=application.email, study_group=study_group).first() application.pk = old_application.pk application.created_at = old_application.created_at #TODO messages.success(request, 'Your signup details have been updated!') if application.mobile and Application.objects.active().filter( mobile=application.mobile, study_group=study_group).exists(): old_application = Application.objects.active().filter( mobile=application.mobile, study_group=study_group).first() application.pk = old_application.pk application.created_at = old_application.created_at #TODO messages.success(request, 'Your signup details have been updated!') # TODO - remove accepted_at or use accepting applications flow application.accepted_at = timezone.now() application.save() url = reverse('studygroups_signup_success', args=(study_group_id, )) return http.HttpResponseRedirect(url) else: form = ApplicationForm(initial={'study_group': study_group}) context = { 'form': form, 'study_group': study_group, } return render(request, 'studygroups/signup.html', context)
def get(self, request, *args, **kwargs): m = get_object_or_404(Recording, pk=kwargs['pk']) u = request.user p = get_or_create_person(request) audio_file = m.audio_file f = request.GET.get('format', 'aac') if f in 'wav': if m.audio_file_wav: audio_file = m.audio_file_wav else: if m.audio_file_aac: audio_file = m.audio_file_aac key = '{0}:{0}:listen'.format(p.uuid, m.id) access = cache.get(key) # logger.debug('CAN VIEW: {0} {1}'.format(key, access)) if (u.is_authenticated() and u.is_staff) or (p == m.person) or (access): try: url = audio_file.path url = audio_file.url except: try: url = self.get_redirect_url(filepath=audio_file.name) except: url = audio_file.url if url: if self.permanent: return http.HttpResponsePermanentRedirect(url) else: return http.HttpResponseRedirect(url) else: logger.warning('Gone: %s', self.request.path, extra={ 'status_code': 410, 'request': self.request }) return http.HttpResponseGone() else: raise http.Http404
def detail(request, name_id): """View for the Name detail page.""" queryset = ( Name.objects.select_related().prefetch_related('identifier_set__type')) name_entry = get_object_or_404(queryset, name_id=name_id) if name_entry.merged_with: return redirect(name_entry.merged_with) elif name_entry.is_suppressed(): return http.HttpResponseNotFound( 'The requested record could not be found.') elif name_entry.is_deleted(): return http.HttpResponseGone('The requested record has been deleted!') return render(request, 'name/name_detail.html', dict(name=name_entry))
def cms_redirect(self, redirect, query): """Returns the response object.""" if not redirect.page and not redirect.new_path: return http.HttpResponseGone() response_class = self.get_cms_redirect_response_class(redirect) if redirect.page: if query: query = '?{query}'.format(query=query) redirect_to = '%s%s' % (redirect.page.get_absolute_url(), query) else: if query and '?' in redirect.new_path: query = '&{query}'.format(query=query) elif query: query = '?{query}'.format(query=query) redirect_to = '%s%s' % (redirect.new_path, query) return response_class(redirect_to)
def process_response(self, request, response): # No need to check for a redirect for non-404 responses. if response.status_code != 404: return response path = request.get_full_path() r = self._redirect_for_path(path) # Try removing the trailing slash. if r is None and path.endswith('/'): r = self._redirect_for_path(path[:-1]) if r is not None: if r.new_path == '': return http.HttpResponseGone() return http.HttpResponsePermanentRedirect(r.sub_path(path)) # No redirect was found. Return the response. return response
def get(self, request, *args, **kwargs): m = get_object_or_404(AnalyticalDocument, pk=kwargs['file_id']) if m.upload: filepath = AWS_ANALYTICAL_MEDIA_LOCATION + '/' + str(m.upload) url = self.get_redirect_url(filepath=filepath) # The below is taken straight from RedirectView. if url: if self.permanent: return http.HttpResponsePermanentRedirect(url) else: return http.HttpResponseRedirect(url) else: logger.warning( 'Gone: %s', self.request.path, extra={'status_code': 410, 'request': self.request}) return http.HttpResponseGone() else: raise http.Http404
def get(self, request, *args, **kwargs): download = get_object_or_404(PrivateDownload, id=kwargs['id']) user = request.user if user.is_authenticated and user.is_staff: url = self.get_redirect_url(filepath=download.private_file.name) # The below is taken straight from RedirectView. if url: if self.permanent: return http.HttpResponsePermanentRedirect(url) else: return http.HttpResponseRedirect(url) else: logger.warning('Gone: %s', self.request.path, extra={ 'status_code': 410, 'request': self.request }) return http.HttpResponseGone() else: raise http.Http404
def get(self, request): token = request.GET.get('token') # 对 token 解密并重新赋值 token = serializer.deserialize(token) # 解密失败或者查询参数中没有 token if token is None: return http.HttpResponseForbidden() try: # 获取需要邮箱激活的用户 user = User.objects.get(id=token.get('id'), email=token.get('email')) # 邮箱激活 user.email_active = True user.save() return redirect('/') except User.DoesNotExist: # 激活失败 return http.HttpResponseGone()
def serve_file_upload(request, uuid): """ This is to serve file uploads using authenticated download URLs. This is currently used by the "scanner" services. """ upload = shortcuts.get_object_or_404(FileUpload, uuid=uuid) access_token = request.GET.get('access_token') if not access_token: log.error('Denying access to %s, no token.', upload.id) raise PermissionDenied if not constant_time_compare(access_token, upload.access_token): log.error('Denying access to %s, token invalid.', upload.id) raise PermissionDenied if not upload.path: log.info('Preventing access to %s, upload path is falsey.' % upload.id) return http.HttpResponseGone('upload path does not exist anymore') return HttpResponseXSendFile( request, upload.path, content_type='application/octet-stream' )
def get_response(self, request): return http.HttpResponseGone()
def process_response(self, request, response): """Accepts a Django request and redirects to a matching myurl""" if response.status_code != 404: return response # remove / from front of URL path = request.get_full_path()[1:] # get the myurl - even if someone appends a trailing / if path.endswith('/'): try: myurl = MyUrl.objects.get( short_path__exact=path[:path.rfind('/')] + path[path.rfind('/') + 1:]) except MyUrl.DoesNotExist: myurl = None else: try: myurl = MyUrl.objects.get(short_path__exact=path) except MyUrl.DoesNotExist: myurl = None # need to put somethign here for failed clicks. # see if myurl is defined # Makes sure we are not redirecting to nowhere if myurl is None: return http.HttpResponseGone() else: # create and save the click history user = None if request.user.is_anonymous else request.user # Store HTTP headers if we have them try: referrer_url = request.META.HTTP_REFERRER except AttributeError: referrer_url = None try: user_domain = request.META.REMOTE_HOST except AttributeError: user_domain = None try: user_language = request.META.HTTP_ACCEPT_LANGUAGE except AttributeError: user_language = None try: user_agent = request.META.HTTP_USER_AGENT except AttributeError: user_agent = None try: user_ip = request.META.REMOTE_ADDR except AttributeError: user_ip = None click = Click(myurl=myurl, to_url=myurl.to_url, redirect_url=myurl.redirect_url, user_domain=user_domain, referrer_url=referrer_url, site_id=settings.SITE_ID, user=user, user_ip=user_ip, user_language=user_language, user_agent=user_agent) click.save() # do the redirect if myurl.redirect_type == '301': return http.HttpResponsePermanentRedirect(myurl.redirect_url) else: return http.HttpResponseRedirect(myurl.redirect_url) # No MyUrl was found. Let Django deal with it. return response
def show(self, request, redirect): if not redirect.redirect_to: return http.HttpResponseGone() return http.HttpResponsePermanentRedirect(redirect.redirect_to)