def process_request(self, request): settings.use_editable() force_host = settings.SSL_FORCE_HOST response = None if force_host and request.get_host().split(":")[0] != force_host: url = "http://%s%s" % (force_host, request.get_full_path()) response = HttpResponsePermanentRedirect(url) elif settings.SSL_ENABLED and not settings.DEV_SERVER: url = "%s%s" % (request.get_host(), request.get_full_path()) if request.path.startswith(settings.SSL_FORCE_URL_PREFIXES): if not request.is_secure(): response = HttpResponseRedirect("https://%s" % url) elif request.is_secure() and settings.SSL_FORCED_PREFIXES_ONLY: response = HttpResponseRedirect("http://%s" % url) if response and request.method == "POST": if resolve(request.get_full_path()).url_name == "fb_do_upload": # The handler for the flash file uploader in filebrowser # doesn't have access to the http headers Django will use # to determine whether the request is secure or not, so # in this case we don't attempt a redirect - note that # when /admin is restricted to SSL using Mezzanine's SSL # setup, the flash uploader will post over SSL, so # someone would need to explictly go out of their way to # trigger this. return # Tell the client they need to re-POST. response.status_code = 307 return response
def logout(request): if request.method != 'GET': raise Http404 else: forward_url = request.GET.get('forward_url','https://weblogin.reed.edu/cgi-bin/logout?http://sin.reed.edu') response = HttpResponsePermanentRedirect(forward_url) response.delete_cookie(key = 'cosign-sin') return response
def __init__(self, redirect_to): #TODO: someday extend to language switching via extra argument if len(redirect_to) > 0 and redirect_to[0] == "/": lang = translation.get_language() path = "/%s%s" % (lang, redirect_to) else: path = redirect_to HttpResponsePermanentRedirect.__init__(self, path)
def process_request(self, request): # Find locale, app prefixer = urlresolvers.Prefixer(request) urlresolvers.set_url_prefix(prefixer) full_path = prefixer.fix(prefixer.shortened_path) if 'lang' in request.GET: # Blank out the locale so that we can set a new one. Remove lang # from query params so we don't have an infinite loop. prefixer.locale = '' new_path = prefixer.fix(prefixer.shortened_path) query = dict((smart_str(k), v) for k, v in request.GET.items() if k not in ('lang', 'locale-only')) response = HttpResponsePermanentRedirect( urlparams(new_path, **query)) xenophobia = 0 # User checked a box is the only reason this would happen. if 'locale-only' in request.GET: xenophobia = 1 response.set_cookie('locale-only', xenophobia, expires=NEXT_YEAR) return response if full_path != request.path: query_string = request.META.get('QUERY_STRING', '') full_path = urllib.quote(full_path.encode('utf-8')) if query_string: full_path = "%s?%s" % (full_path, query_string) response = HttpResponsePermanentRedirect(full_path) # Vary on Accept-Language if we changed the locale. old_locale = prefixer.locale new_locale, _, _ = prefixer.split_path(full_path) if old_locale != new_locale: response['Vary'] = 'Accept-Language' return response request.path_info = '/' + prefixer.shortened_path tower.activate(prefixer.locale) request.APP = amo.APPS.get(prefixer.app) request.LANG = prefixer.locale if 'locale-only' in request.COOKIES: request.XENOPHOBIA = (request.COOKIES['locale-only'] == '1') else: try: conf = Config.objects.get(pk='xenophobia') request.XENOPHOBIA = conf.json.get( translation.get_language(), False) except Config.DoesNotExist: request.XENOPHOBIA = False
def logout_user(request): logout(request) # return # HttpResponseRedirect('https://weblogin.reed.edu/cgi-bin/logout?https://cs.reed.edu/logged_out/') forward_url = request.GET.get( 'forward_url', 'https://weblogin.reed.edu/cgi-bin/logout?https://cs.reed.edu/logged_out/') response = HttpResponsePermanentRedirect(forward_url) response.delete_cookie(key='cosign-cs') return response
def index_submit(request): response = HttpResponsePermanentRedirect("/schedule/") if request.method == "POST": form = forms.CourseForm(request.POST) if form.is_valid(): sessionCourseString = "" list_of_courses = getcourses.get_section_list(form.cleaned_data["courses"]) for courseName in list_of_courses: sessionCourseString += courseName + "," # request.session['section_list'] = dict(list_of_courses) import json # response.set_cookie('section_list', str(list_of_courses)) # request.session['courses_string'] = sessionCourseString response.set_cookie("courses_string", sessionCourseString) return response return HttpResponsePermanentRedirect("/")
def index_submit(request): response = HttpResponsePermanentRedirect('/schedule/') if request.method == 'POST': form = forms.CourseForm(request.POST) if form.is_valid(): sessionCourseString = '' list_of_courses = getcourses.get_section_list(form.cleaned_data['courses']) if (list_of_courses != None): for courseName in list_of_courses: sessionCourseString += courseName + ',' # request.session['section_list'] = dict(list_of_courses) import json # response.set_cookie('section_list', str(list_of_courses)) # request.session['courses_string'] = sessionCourseString response.set_cookie('courses_string',sessionCourseString) return response return HttpResponsePermanentRedirect('/')
def process_request(self, request): prefixer = urlresolvers.Prefixer(request) urlresolvers.set_url_prefix(prefixer) full_path = prefixer.fix(prefixer.shortened_path) if 'lang' in request.GET: # Blank out the locale so that we can set a new one. Remove lang # from the query params so we don't have an infinite loop. prefixer.locale = '' new_path = prefixer.fix(prefixer.shortened_path) query = dict((smart_str(k), request.GET[k]) for k in request.GET) query.pop('lang') response = HttpResponsePermanentRedirect(urlparams(new_path, **query)) response.set_cookie('lang', request.GET['lang']) return response if full_path != request.path: query_string = request.META.get('QUERY_STRING', '') full_path = urllib.quote(full_path.encode('utf-8')) if query_string: full_path = '%s?%s' % (full_path, query_string) response = HttpResponsePermanentRedirect(full_path) # Vary on Accept-Language if we changed the locale old_locale = prefixer.locale new_locale, _ = prefixer.split_path(full_path) if old_locale != new_locale: response['Vary'] = 'Accept-Language' return response request.path_info = '/' + prefixer.shortened_path request.locale = prefixer.locale tower.activate(prefixer.locale)
def search(request, deal_type, property_type, regions_slug=None, show_result=None): region = Region.get_region_from_slug(regions_slug, '' if request.subdomain == 'bank' else request.subdomain, request.subdomain_region) if not region: raise Http404 # весь список объявлений с указанном типом объявления items_list = Ad.objects.filter(bank__isnull=False, is_published=True, deal_type__in=deal_type.split(',')).exclude(get_exclude_rules())\ .prefetch_related('region','photos','user') # применяем фильтр по регионам items_list = items_list.filter(region__in=region.get_descendants(True)) ad_property_types = convert_to_ad(property_type) items_list = items_list.filter(property_type__in=ad_property_types) min_price, max_price = get_price_range('%s_%s_%s_bank' % (deal_type, property_type, region.pk), items_list) # применяем фильтры поиска if len(request.GET) > 0: form = PropertySearchForm(request.GET) # A form bound to the POST data if form.is_valid(): if not (len(request.GET)== 1 and 'property_type' in request.GET): show_result = True # currency rate curr_rate = 1 if ('currency' in form.cleaned_data and form.cleaned_data['currency'] and form.cleaned_data['currency'] != 'UAH') and ((form.cleaned_data['price_from'] > 0) or (form.cleaned_data['price_to'] > 0)): from utils.currency import get_currency_rates curr_rate = get_currency_rates()[form.cleaned_data['currency']] if form.cleaned_data['price_from'] > 0: items_list = items_list.filter(price_uah__gte=form.cleaned_data['price_from'] * curr_rate) if form.cleaned_data['price_to'] > 0: items_list = items_list.filter(price_uah__lte=form.cleaned_data['price_to'] * curr_rate) if form.cleaned_data['rooms']: Q_rooms = Q() for room in form.cleaned_data['rooms']: if room.find('+') > 0: Q_rooms = Q_rooms | Q(rooms__gte=room[:-1]) else: Q_rooms = Q_rooms | Q(rooms=room) items_list = items_list.filter(Q_rooms) if form.cleaned_data['property_commercial_type']: items_list = items_list.filter(property_commercial_type=form.cleaned_data['property_commercial_type']) if form.cleaned_data['with_image'] > 0: items_list = items_list.filter(has_photos=True) if form.cleaned_data['without_commission'] > 0: items_list = items_list.filter(without_commission=True) if form.cleaned_data['sort']: items_list = items_list.order_by(form.cleaned_data['sort']) # ключевые слова if form.cleaned_data['keywords'] != '': keywords = form.cleaned_data['keywords'].split(',') criterions = Q() for keyword in keywords: keyword = keyword.strip() selected_region = _check_region_subdomain(keyword) if type(selected_region) == Region: if selected_region != region: kwargs = {'property_type': property_type} region_slug = selected_region.get_region_slug() if region_slug: kwargs['regions_slug'] = region_slug url = selected_region.get_host_url('bank-ad-search-result', host='bank', kwargs=kwargs) return HttpResponsePermanentRedirect(url) criterions.add(Q(description__icontains=keyword) | Q(address__icontains=keyword), Q.AND) items_list = items_list.filter(criterions) else: try: # в __init__ подготовка списка регионов для формы form = PropertySearchForm(request.GET) except Region.DoesNotExist: # не найден активный регион в выпадающем списке return redirect('..') if not show_result: items_list = items_list.filter(has_photos=True).order_by('-updated') items_list = items_list[:4] else: pass items_list = items_list.prefetch_related('photos') paginator = HandyPaginator(items_list, 10, request=request) seo_klass = SEO(current_language=settings.LANGUAGE_CODE) seo = seo_klass.get_seo( region=region, deal_type=deal_type, property_type=ad_property_types[0], ) return render(request, 'bank/search.html', locals())
def redirect_project_to_projects(request, project__name): new_url = reverse(project, kwargs={'project__name': project__name}) return HttpResponsePermanentRedirect(new_url)
def article_print_xml(request, channel, slug): return HttpResponsePermanentRedirect( reverse('article_show', args=[channel, slug]))
def ticketAuth(request, ticketId): ''' Used to authenticate an user via a ticket ''' try: data = TicketStore.get(ticketId, invalidate=True) try: # Extract ticket.data from ticket.data storage, and remove it if success username = data['username'] groups = data['groups'] auth = data['auth'] realname = data['realname'] servicePool = data['servicePool'] password = data['password'] transport = data['transport'] except Exception: logger.error('Ticket stored is not valid') raise InvalidUserException() auth = Authenticator.objects.get(uuid=auth) # If user does not exists in DB, create it right now # Add user to groups, if they exists... grps = [] for g in groups: try: grps.append(auth.groups.get(uuid=g)) except Exception: logger.debug('Group list has changed since ticket assignment') if len(grps) == 0: logger.error('Ticket has no valid groups') raise Exception('Invalid ticket authentication') usr = auth.getOrCreateUser(username, realname) if usr is None or State.isActive( usr.state) is False: # If user is inactive, raise an exception raise InvalidUserException() # Add groups to user (replace existing groups) usr.groups = grps # Force cookie generation webLogin(request, None, usr, password) request.user = usr # Temporarily store this user as "authenticated" user, next requests will be done using session request.session[ 'ticket'] = '1' # Store that user access is done using ticket logger.debug("Service & transport: {}, {}".format( servicePool, transport)) for v in DeployedService.objects.all(): logger.debug("{} {}".format(v.uuid, v.name)) # Check if servicePool is part of the ticket if servicePool is not None: # If service pool is in there, also is transport res = userServiceManager().getService(request.user, request.ip, 'F' + servicePool, transport, False) _x, userService, _x, transport, _x = res transportInstance = transport.getInstance() if transportInstance.ownLink is True: link = reverse('TransportOwnLink', args=('A' + userService.uuid, transport.uuid)) else: link = html.udsAccessLink(request, 'A' + userService.uuid, transport.uuid) response = render(request, theme.template('simpleLauncher.html'), {'link': link}) else: response = HttpResponsePermanentRedirect( reverse('uds.web.views.index')) # Now ensure uds cookie is at response getUDSCookie(request, response, True) return response except ServiceNotReadyError as e: return render(request, theme.template('service_not_ready.html'), { 'fromLauncher': True, 'code': e.code }) except TicketStore.InvalidTicket: return render(request, theme.template('simpleLauncherAlreadyLaunched.html')) except Authenticator.DoesNotExist: logger.error('Ticket has an non existing authenticator') return errors.exceptionView(request, InvalidUserException()) except DeployedService.DoesNotExist: logger.error('Ticket has an invalid Service Pool') return errors.exceptionView(request, InvalidServiceException()) except Exception as e: logger.exception('Exception') return errors.exceptionView(request, e)
def sneakpeek_redirect(request, *args, **kwargs): return HttpResponsePermanentRedirect(request.event.urls.featured)
def product_details(request, slug, product_id, form=None): """Product details page The following variables are available to the template: product: The Product instance itself. is_visible: Whether the product is visible to regular users (for cases when an admin is previewing a product before publishing). form: The add-to-cart form. price_range: The PriceRange for the product including all discounts. undiscounted_price_range: The PriceRange excluding all discounts. discount: Either a Price instance equal to the discount value or None if no discount was available. local_price_range: The same PriceRange from price_range represented in user's local currency. The value will be None if exchange rate is not available or the local currency is the same as site's default currency. """ products = products_with_details(user=request.user) product = get_object_or_404(products, id=product_id) if product.get_slug() != slug: return HttpResponsePermanentRedirect(product.get_absolute_url()) today = datetime.date.today() is_visible = (product.available_on is None or product.available_on <= today) if form is None: form = handle_cart_form(request, product, create_cart=False)[0] availability = get_availability(product, discounts=request.discounts, local_currency=request.currency) template_name = 'product/details_%s.html' % ( type(product).__name__.lower(), ) templates = [template_name, 'product/details.html'] product_images = get_product_images(product) variant_picker_data = get_variant_picker_data(product, request.discounts, request.currency) product_attributes = get_product_attributes_data(product) show_variant_picker = all([v.attributes for v in product.variants.all()]) json_ld_data = product_json_ld(product, availability, product_attributes) return TemplateResponse( request, templates, { 'is_visible': is_visible, 'form': form, 'availability': availability, 'product': product, 'product_attributes': product_attributes, 'product_images': product_images, 'show_variant_picker': show_variant_picker, 'variant_picker_data': json.dumps(variant_picker_data, default=serialize_decimal), 'json_ld_product_data': json.dumps(json_ld_data, default=serialize_decimal) })
def builds_redirect_list(request, project_slug): return HttpResponsePermanentRedirect( reverse('builds_project_list', args=[project_slug]))
def login(request): user = users.get_current_user() if user: return HttpResponseRedirect('/') else: return HttpResponsePermanentRedirect(users.create_login_url(request.get_full_path()))
def newRoot(request): try: grid_view = reverse('reports_grid_view') except NoReverseMatch: grid_view = '/grid' return HttpResponsePermanentRedirect(grid_view)
def remove_projects_redirect(request): return HttpResponsePermanentRedirect(request.path.replace('/projects/', '/'))
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)
def document(request, document_slug, document_locale): """ View a wiki document. """ # PUT requests go to the write API. if request.method == 'PUT': if (not request.authkey and not request.user.is_authenticated()): raise PermissionDenied return _document_PUT(request, document_slug, document_locale) fallback_reason = None slug_dict = split_slug(document_slug) # Is there a document at this slug, in this locale? doc, fallback_reason = _get_doc_and_fallback_reason( document_locale, document_slug) if doc is None: # Possible the document once existed, but is now deleted. # If so, show that it was deleted. deletion_log_entries = DocumentDeletionLog.objects.filter( locale=document_locale, slug=document_slug) if deletion_log_entries.exists(): return _document_deleted(request, deletion_log_entries) # We can throw a 404 immediately if the request type is HEAD. # TODO: take a shortcut if the document was found? if request.method == 'HEAD': raise Http404 # Check if we should fall back to default locale. fallback_doc, fallback_reason, redirect_url = _default_locale_fallback( request, document_slug, document_locale) if fallback_doc is not None: doc = fallback_doc if redirect_url is not None: return redirect(redirect_url) else: # If a Document is not found, we may 404 immediately based on # request parameters. if (any([ request.GET.get(param, None) for param in ('raw', 'include', 'nocreate') ]) or not request.user.is_authenticated()): raise Http404 # The user may be trying to create a child page; if a parent exists # for this document, redirect them to the "Create" page # Otherwise, they could be trying to create a main level doc. create_url = _document_redirect_to_create(document_slug, document_locale, slug_dict) return redirect(create_url) # We found a Document. Now we need to figure out how we're going # to display it. # If we're a redirect, and redirecting hasn't been disabled, redirect. # Obey explicit redirect pages: # Don't redirect on redirect=no (like Wikipedia), so we can link from a # redirected-to-page back to a "Redirected from..." link, so you can edit # the redirect. redirect_url = (None if request.GET.get('redirect') == 'no' else doc.get_redirect_url()) if redirect_url and redirect_url != doc.get_absolute_url(): url = urlparams(redirect_url, query_dict=request.GET) # TODO: Re-enable the link in this message after Django >1.5 upgrade # Redirected from <a href="%(url)s?redirect=no">%(url)s</a> messages.add_message( request, messages.WARNING, mark_safe( ugettext(u'Redirected from %(url)s') % {"url": request.build_absolute_uri(doc.get_absolute_url())}), extra_tags='wiki_redirect') return HttpResponsePermanentRedirect(url) # Read some request params to see what we're supposed to do. rendering_params = {} for param in ('raw', 'summary', 'include', 'edit_links'): rendering_params[param] = request.GET.get(param, False) is not False rendering_params['section'] = request.GET.get('section', None) rendering_params['render_raw_fallback'] = False rendering_params['use_rendered'] = kumascript.should_use_rendered( doc, request.GET) # Get us some HTML to play with. doc_html, ks_errors, render_raw_fallback = _get_html_and_errors( request, doc, rendering_params) rendering_params['render_raw_fallback'] = render_raw_fallback toc_html = None # Start parsing and applying filters. if not doc.is_template: if doc.show_toc and not rendering_params['raw']: toc_html = doc.get_toc_html() else: toc_html = None doc_html = _filter_doc_html(request, doc, doc_html, rendering_params) # If we're doing raw view, bail out to that now. if rendering_params['raw']: return _document_raw(request, doc, doc_html, rendering_params) # Get the SEO summary seo_summary = '' if not doc.is_template: seo_summary = doc.get_summary_text() # Get the additional title information, if necessary. seo_parent_title = _get_seo_parent_title(slug_dict, document_locale) # Retrieve pre-parsed content hunks if doc.is_template: quick_links_html, zone_subnav_html = None, None body_html = doc_html else: quick_links_html = doc.get_quick_links_html() zone_subnav_html = doc.get_zone_subnav_html() body_html = doc.get_body_html() share_text = ugettext('I learned about %(title)s on MDN.') % { "title": doc.title } contributors = doc.contributors contributors_count = len(contributors) has_contributors = contributors_count > 0 # Bundle it all up and, finally, return. context = { 'document': doc, 'document_html': doc_html, 'toc_html': toc_html, 'quick_links_html': quick_links_html, 'zone_subnav_html': zone_subnav_html, 'body_html': body_html, 'contributors': contributors, 'contributors_count': contributors_count, 'contributors_limit': 6, 'has_contributors': has_contributors, 'fallback_reason': fallback_reason, 'kumascript_errors': ks_errors, 'render_raw_fallback': rendering_params['render_raw_fallback'], 'seo_summary': seo_summary, 'seo_parent_title': seo_parent_title, 'share_text': share_text, 'search_url': referrer_url(request) or '', } response = render(request, 'wiki/document.html', context) return _set_common_headers(doc, rendering_params['section'], response)
problem.problem_submit, name='problem_submit'), url( r'^/rank/', paged_list_view(ranked_submission.RankedSubmissions, 'ranked_submissions')), url( r'^/submissions/', paged_list_view(submission.ProblemSubmissions, 'chronological_submissions')), url( r'^/submissions/(?P<user>\w+)/', paged_list_view(submission.UserProblemSubmissions, 'user_submissions')), url( r'^/$', lambda _, problem: HttpResponsePermanentRedirect( reverse('problem_detail', args=[problem]))), url(r'^/test_data$', ProblemDataView.as_view(), name='problem_data'), url(r'^/test_data/init$', problem_init_view, name='problem_data_init'), url(r'^/test_data/diff$', ProblemSubmissionDiff.as_view(), name='problem_submission_diff'), url(r'^/data/(?P<path>.+)$', problem_data_file, name='problem_data_file'), url(r'^/tickets$', ticket.ProblemTicketListView.as_view(), name='problem_ticket_list'),
def get_response(self, request): '''Returns the redirect response for this exception.''' response = HttpResponsePermanentRedirect(self.redirect_to, *self.args, **self.kwargs) response[REDIRECT_HEADER_KEY] = self.redirect_to return response
def skill_details(request, slug, skill_id, form=None): """Skill details page. The following variables are available to the template: skill: The Skill instance itself. is_visible: Whether the skill is visible to regular users (for cases when an admin is previewing a skill before publishing). form: The add-to-cart form. price_range: The PriceRange for the skill including all discounts. undiscounted_price_range: The PriceRange excluding all discounts. discount: Either a Price instance equal to the discount value or None if no discount was available. local_price_range: The same PriceRange from price_range represented in user's local currency. The value will be None if exchange rate is not available or the local currency is the same as site's default currency. """ print("Skill") skills = skills_with_details(user=request.user) skill = get_object_or_404(skills, id=skill_id) if skill.get_slug() != slug: return HttpResponsePermanentRedirect(skill.get_absolute_url()) today = datetime.date.today() is_visible = (skill.publication_date is None or skill.publication_date <= today) if form is None: form = handle_cart_form(request, skill, create_cart=False)[0] availability = get_availability(skill, discounts=request.discounts, taxes=request.taxes, local_currency=request.currency) skill_images = get_skill_images(skill_type) variant_picker_data = get_variant_picker_data(skill, request.discounts, request.taxes, request.currency) skill_attributes = get_skill_attributes_data(skill) # show_variant_picker determines if variant picker is used or select input show_variant_picker = all([v.attributes for v in skill.variants.all()]) json_ld_data = skill_json_ld(skill, skill_attributes) ctx = { 'is_visible': is_visible, 'form': form, 'availability': availability, 'skill': skill, 'skill_attributes': skill_attributes, 'skill_images': skill_images, 'show_variant_picker': show_variant_picker, 'variant_picker_data': json.dumps(variant_picker_data, default=serialize_decimal), 'json_ld_skill_data': json.dumps(json_ld_data, default=serialize_decimal) } return TemplateResponse(request, 'skill/details.html', ctx)
def __call__(self, request): if request.get_host() in settings.LEGACY_HOSTS: return HttpResponsePermanentRedirect( urljoin(settings.SITE_URL, request.get_full_path())) return self.get_response(request)
def builds_redirect_detail(request, project_slug, pk): return HttpResponsePermanentRedirect( reverse('builds_detail', args=[project_slug, pk]))
def process_request(self, request): """Process the given request""" asset_path = request.path if self.is_asset_request(request): # lint-amnesty, pylint: disable=too-many-nested-blocks # Make sure we can convert this request into a location. if AssetLocator.CANONICAL_NAMESPACE in asset_path: asset_path = asset_path.replace('block/', 'block@', 1) # If this is a versioned request, pull out the digest and chop off the prefix. requested_digest = None if StaticContent.is_versioned_asset_path(asset_path): requested_digest, asset_path = StaticContent.parse_versioned_asset_path(asset_path) # Make sure we have a valid location value for this asset. try: loc = StaticContent.get_location_from_path(asset_path) except (InvalidLocationError, InvalidKeyError): return HttpResponseBadRequest() # Attempt to load the asset to make sure it exists, and grab the asset digest # if we're able to load it. actual_digest = None try: content = self.load_asset_from_location(loc) actual_digest = getattr(content, "content_digest", None) except (ItemNotFoundError, NotFoundError): return HttpResponseNotFound() # If this was a versioned asset, and the digest doesn't match, redirect # them to the actual version. if requested_digest is not None and actual_digest is not None and (actual_digest != requested_digest): actual_asset_path = StaticContent.add_version_to_asset_path(asset_path, actual_digest) return HttpResponsePermanentRedirect(actual_asset_path) # Set the basics for this request. Make sure that the course key for this # asset has a run, which old-style courses do not. Otherwise, this will # explode when the key is serialized to be sent to NR. safe_course_key = loc.course_key if safe_course_key.run is None: safe_course_key = safe_course_key.replace(run='only') if newrelic: newrelic.agent.add_custom_parameter('course_id', safe_course_key) newrelic.agent.add_custom_parameter('org', loc.org) newrelic.agent.add_custom_parameter('contentserver.path', loc.path) # Figure out if this is a CDN using us as the origin. is_from_cdn = StaticContentServer.is_cdn_request(request) newrelic.agent.add_custom_parameter('contentserver.from_cdn', is_from_cdn) # Check if this content is locked or not. locked = self.is_content_locked(content) newrelic.agent.add_custom_parameter('contentserver.locked', locked) # Check that user has access to the content. if not self.is_user_authorized(request, content, loc): return HttpResponseForbidden('Unauthorized') # Figure out if the client sent us a conditional request, and let them know # if this asset has changed since then. last_modified_at_str = content.last_modified_at.strftime(HTTP_DATE_FORMAT) if 'HTTP_IF_MODIFIED_SINCE' in request.META: if_modified_since = request.META['HTTP_IF_MODIFIED_SINCE'] if if_modified_since == last_modified_at_str: return HttpResponseNotModified() # *** File streaming within a byte range *** # If a Range is provided, parse Range attribute of the request # Add Content-Range in the response if Range is structurally correct # Request -> Range attribute structure: "Range: bytes=first-[last]" # Response -> Content-Range attribute structure: "Content-Range: bytes first-last/totalLength" # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 response = None if request.META.get('HTTP_RANGE'): # If we have a StaticContent, get a StaticContentStream. Can't manipulate the bytes otherwise. if isinstance(content, StaticContent): content = AssetManager.find(loc, as_stream=True) header_value = request.META['HTTP_RANGE'] try: unit, ranges = parse_range_header(header_value, content.length) except ValueError as exception: # If the header field is syntactically invalid it should be ignored. log.exception( "%s in Range header: %s for content: %s", str(exception), header_value, str(loc) ) else: if unit != 'bytes': # Only accept ranges in bytes log.warning("Unknown unit in Range header: %s for content: %s", header_value, str(loc)) elif len(ranges) > 1: # According to Http/1.1 spec content for multiple ranges should be sent as a multipart message. # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.16 # But we send back the full content. log.warning( "More than 1 ranges in Range header: %s for content: %s", header_value, str(loc) ) else: first, last = ranges[0] if 0 <= first <= last < content.length: # If the byte range is satisfiable response = HttpResponse(content.stream_data_in_range(first, last)) response['Content-Range'] = 'bytes {first}-{last}/{length}'.format( first=first, last=last, length=content.length ) response['Content-Length'] = str(last - first + 1) response.status_code = 206 # Partial Content if newrelic: newrelic.agent.add_custom_parameter('contentserver.ranged', True) else: log.warning( "Cannot satisfy ranges in Range header: %s for content: %s", header_value, str(loc) ) return HttpResponse(status=416) # Requested Range Not Satisfiable # If Range header is absent or syntactically invalid return a full content response. if response is None: response = HttpResponse(content.stream_data()) response['Content-Length'] = content.length if newrelic: newrelic.agent.add_custom_parameter('contentserver.content_len', content.length) newrelic.agent.add_custom_parameter('contentserver.content_type', content.content_type) # "Accept-Ranges: bytes" tells the user that only "bytes" ranges are allowed response['Accept-Ranges'] = 'bytes' response['Content-Type'] = content.content_type response['X-Frame-Options'] = 'ALLOW' # Set any caching headers, and do any response cleanup needed. Based on how much # middleware we have in place, there's no easy way to use the built-in Django # utilities and properly sanitize and modify a response to ensure that it is as # cacheable as possible, which is why we do it ourselves. self.set_caching_headers(content, response) return response
def get(self, request, *args, **kwargs): path = kwargs.get('path', '') return HttpResponsePermanentRedirect('/p/' + path)
def process_request(self, request): host = request.get_host() if settings.REMOVE_WWW and host and host.startswith('www.'): redirect_url = '%s://%s%s' % (request.scheme, host[4:], request.get_full_path()) return HttpResponsePermanentRedirect(redirect_url)
def get(self, request, *args, **kwargs): self.object = self.get_object() if self.object.slug != kwargs['slug']: return HttpResponsePermanentRedirect(reverse('organization_home', args=(self.object.id, self.object.slug))) context = self.get_context_data(object=self.object) return self.render_to_response(context)
def favicon(request): icon = LayoutSettings.for_site(request.site).favicon if icon: return HttpResponsePermanentRedirect( icon.get_rendition('original').url) raise Http404()
def new(request): # Remove legacy query parameters (Bug 1236791) if request.GET.get('product', None) or request.GET.get('os', None): return HttpResponsePermanentRedirect(reverse('firefox.new')) scene = request.GET.get('scene', None) # note: v and xv params only allow a-z, A-Z, 0-9, -, and _ charcaters experience = request.GET.get('xv', None) variant = request.GET.get('v', None) locale = l10n_utils.get_locale(request) # ensure variant matches pre-defined value if variant not in ['a', 'b', 'c']: # place expected ?v= values in this list variant = None if scene == '2': # send to new permanent scene2 URL (bug 1438302) thanks_url = reverse('firefox.download.thanks') query_string = request.META.get('QUERY_STRING', '') if query_string: thanks_url = '?'.join( [thanks_url, force_text(query_string, errors='ignore')]) return HttpResponsePermanentRedirect(thanks_url) # if no/incorrect scene specified, show scene 1 else: if locale == 'de': if experience == 'berlin': template = 'firefox/new/berlin/scene1.html' elif experience == 'aus-gruenden': template = 'firefox/new/berlin/scene1-aus-gruenden.html' elif experience == 'herz': template = 'firefox/new/berlin/scene1-herz.html' elif experience == 'geschwindigkeit': template = 'firefox/new/berlin/scene1-gesch.html' elif experience == 'privatsphare': template = 'firefox/new/berlin/scene1-privat.html' elif experience == 'auf-deiner-seite': template = 'firefox/new/berlin/scene1-auf-deiner-seite.html' else: template = 'firefox/new/scene1.html' elif switch('firefox-yandex') and locale == 'ru': template = 'firefox/new/yandex/scene1.html' elif locale == 'en-US': if experience == 'betterbrowser': template = 'firefox/new/better-browser/scene1.html' elif experience == 'safari': template = 'firefox/new/compare/scene1-safari.html' elif experience == 'edge': template = 'firefox/new/compare/scene1-edge.html' elif variant in ['a', 'b', 'c']: template = 'firefox/new/install/scene1.html' else: template = 'firefox/new/scene1.html' else: template = 'firefox/new/scene1.html' # no harm done by passing 'v' to template, even when no experiment is running # (also makes tests easier to maintain by always sending a context) return l10n_utils.render(request, template, { 'experience': experience, 'v': variant })
def toplevel(request): return HttpResponsePermanentRedirect("/search/")
def detail(request, pk, slug=None): item = get_object_or_404(Herbarium.objects.select_related('kind'), pk=pk) if item.slug != slug: return HttpResponsePermanentRedirect(item.get_absolute_url()) return render(request, 'fruit/herbarium.html', {'detail': item})
def product_detail(request, slug, id): try: product = Product.objects.get_product(id, request) except Product.DoesNotExist: raise Http404 _client = request.client.client # raise 404 if there is no such product if not product: raise Http404 else: primary_rate_chart = product.primary_rate_chart() if not primary_rate_chart: raise Http404 if not primary_rate_chart.seller.client == request.client.client: raise Http404 # to ensure proper seo rank, we redirect to url based on current slug if product.slug != slug: return HttpResponsePermanentRedirect( reverse('product-detail-url', None, kwargs={ 'slug': product.slug, 'id': id })) if request.method == 'GET': sort = request.GET.get('sort', "MostHelpful") utils.track_product_view_usage(request, product) avg_rating = 0 rating_list = [0, 0, 0, 0, 0] bar_width = [0, 0, 0, 0, 0] product_reviews = Review.objects.filter(product=product, status__in=['approved']).order_by( '-no_helpful', 'no_not_helpful', '-reviewed_on') total_reviews = len(product_reviews) if product_reviews: for review in product_reviews: avg_rating += review.rating if review.rating == 5: rating_list[0] += 1 elif review.rating == 4: rating_list[1] += 1 elif review.rating == 3: rating_list[2] += 1 elif review.rating == 2: rating_list[3] += 1 else: rating_list[4] += 1 for a in [0, 1, 2, 3, 4]: bar_width[a] = Decimal( rating_list[a] / Decimal(len(product_reviews))) * 160 avg_rating = Decimal(avg_rating) / Decimal(len(product_reviews)) upper_limit = Decimal(str(math.ceil(avg_rating))) - (avg_rating) if upper_limit >= Decimal('0.75'): avg_rating = int(avg_rating) + 0.25 elif upper_limit >= Decimal('0.5'): avg_rating = int(avg_rating) + 0.5 elif upper_limit >= Decimal('0.25'): avg_rating = int(avg_rating) + 0.75 elif upper_limit < Decimal('0.25') and upper_limit != Decimal('0.0'): avg_rating = int(avg_rating) + 1 avg_rating = float(avg_rating) product_reviews = product_reviews[0:5] pdp_review_length = len(product_reviews) rated_check = {} if request.user.is_authenticated(): profiles = Profile.objects.filter(user=request.user).order_by('id') profile = profiles[0] for review in product_reviews: helpfulness = ReviewHelpfulness.objects.filter(review=review, user=profile) try: helpfulness = helpfulness[0] except: pass if helpfulness: rated_check[review.id] = helpfulness.status else: rated_check[review.id] = 'NULL' offer_price = product.primary_rate_chart().offer_price product_images = product.get_product_images() offer_price = product.primary_rate_chart().offer_price priceInfo = {} priceInfo = product.primary_rate_chart().getPriceInfo(request) offer_price = priceInfo['offer_price'] emi = None emi = utils.compute_emi(offer_price) similar_products = product.similar_products(request)[:5] sProds = similar_products rating_dict = {} for a in range(0, 5): rating_dict[a] = [rating_list[a], bar_width[a]] product_dict = { "product_images": product_images, "product": product, "rate_chart": product.primary_rate_chart(), "similarProducts": sProds, "emi": emi, # "form":form, "product_reviews": product_reviews, "total_reviews": total_reviews, "avg_rating": avg_rating, "price_info": priceInfo, "sort": sort, "rating_dict": rating_dict, "rated_check": rated_check, "pdp_review_length": pdp_review_length, "slug": slug } return render_to_response('products/product.html', product_dict, context_instance=RequestContext(request))
def diff_redirect(request): return HttpResponsePermanentRedirect( reverse('pushes:diff') + '?' + request.GET.urlencode())
def process_request(self, request): host = request.get_host() if host.startswith("www."): return HttpResponsePermanentRedirect("https://%s/" % host[4:])
def redirect_report_card(request, entity_name, chembl_id,): url_name = ENTITY_NAME_TO_URL_NAME[entity_name] return HttpResponsePermanentRedirect(reverse(url_name, args=[chembl_id.upper()]))
def pushlog_redirect(request, path): return HttpResponsePermanentRedirect( reverse('pushes:pushlog', kwargs={'repo_name': path}) + '?' + request.GET.urlencode())