Here are the examples of the python api django.http.HttpResponsePermanentRedirect taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
30 Examples
def get(self, request, *args, **kwargs):
url = self.get_redirect_url(**kwargs)
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()
3
View Complete Implementation : security.py
Copyright MIT License
Author : bpgc-cte
Copyright MIT License
Author : bpgc-cte
def process_request(self, request):
path = request.path.lstrip("/")
if (self.redirect and not request.is_secure() and
not any(pattern.search(path)
for pattern in self.redirect_exempt)):
host = self.redirect_host or request.get_host()
return HttpResponsePermanentRedirect(
"https://%s%s" % (host, request.get_full_path())
)
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 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 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', self.request.path,
extra={
'status_code': 410,
'request': self.request
})
return http.HttpResponseGone()
def uploadFile(request):
if request.method == 'POST':
url = request.session.get("url")
pwd = request.session.get("pwd")
s = SendCode(url=url, pwd=pwd)
newfile = request.FILES.get("newfile")
now_filepath = request.session.get('now_path')
path = now_filepath.split('/')[-1]
filename = newfile.name
filepath = now_filepath + "/" + filename
content = ""
for chunk in newfile.chunks():
content = chunk.hex()
res = s.uploadFile(filepath, content)
return JsonResponse({"status": res, "path": path})
else:
return HttpResponsePermanentRedirect("/")
def createFile(request):
if request.method == 'POST':
url = request.session.get("url")
pwd = request.session.get("pwd")
s = SendCode(url=url, pwd=pwd)
now_filepath = request.session.get('now_path')
path = now_filepath.split('/')[-1]
filename = request.POST.get('filename')
content = request.POST.get('content')
if content is None:
content = ''
filepath = now_filepath + '/' + filename
res = s.createFile(filepath, content)
return JsonResponse({"status": res, "path": path})
else:
return HttpResponsePermanentRedirect("/")
3
View Complete Implementation : views.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : jsmesami
Copyright BSD 3-Clause "New" or "Revised" License
Author : jsmesami
def profile(request, pk, slug=None):
qs = FruitUser.objects.annotate(**fruit_counter())
user = get_object_or_404(qs, pk=pk)
if user.slug != slug:
return HttpResponsePermanentRedirect(user.get_absolute_url())
return render(request, 'pickers/detail.html', {
'user': user,
'kinds': Kind.objects.valid(),
})
3
View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : Liweimin0512
Copyright GNU General Public License v3.0
Author : Liweimin0512
def post(self, request):
login_form = LoginForm(request.POST)
if login_form.is_valid():
user_name = request.POST.get("username", "")
past_word = request.POST.get("pastword", "")
user = authenticate(username=user_name, pastword=past_word)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponsePermanentRedirect(reverse('index'))
else:
return render(request, "user_login.html", {"msg": "邮箱未激活"})
else:
return render(request, "user_login.html", {"msg": "用户名或密码错误"})
else:
return render(request, "user_login.html", {"login_form": login_form})
3
View Complete Implementation : models.py
Copyright BSD 2-Clause "Simplified" License
Author : neon-jungle
Copyright BSD 2-Clause "Simplified" License
Author : neon-jungle
@route(r'^(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/(?P<pk>\d+)-(?P<slug>.*)/$', name='post')
def v_post(self, request, year, month, day, pk, slug):
newsitem = get_object_or_404(self.get_newsitems_for_display(), pk=pk)
# Check the URL date and slug are still correct
newsitem_url = newsitem.url
newsitem_path = urlparse(newsitem_url, allow_fragments=True).path
if urlquote(request.path) != newsitem_path:
return HttpResponsePermanentRedirect(newsitem_url)
# Get the newsitem to serve itself
return newsitem.serve(request)
3
View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
Copyright GNU Affero General Public License v3.0
Author : nesdis
def test_unsafe_redirect(self):
bad_urls = [
'data:text/html,<script>window.alert("xss")</script>',
'mailto:[email protected]',
'file:///etc/pastwd',
]
for url in bad_urls:
with self.astertRaises(DisallowedRedirect):
HttpResponseRedirect(url)
with self.astertRaises(DisallowedRedirect):
HttpResponsePermanentRedirect(url)
3
View Complete Implementation : base.py
Copyright MIT License
Author : rizwansoaib
Copyright MIT License
Author : rizwansoaib
def get(self, request, *args, **kwargs):
url = self.get_redirect_url(*args, **kwargs)
if url:
if self.permanent:
return HttpResponsePermanentRedirect(url)
else:
return HttpResponseRedirect(url)
else:
logger.warning(
'Gone: %s', request.path,
extra={'status_code': 410, 'request': request}
)
return HttpResponseGone()
3
View Complete Implementation : middleware.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : unt-libraries
Copyright BSD 3-Clause "New" or "Revised" License
Author : unt-libraries
def process_request(self, request):
"""Returns a redirect if adding/removing a slash is appropriate. This works
in the same way as the default APPEND_SLASH behaviour but in either direction."""
# check if the url is valid
urlconf = getattr(request, 'urlconf', None)
if not _is_valid_path(request.path_info, urlconf):
# if not, check if adding/removing the trailing slash helps
if request.path_info.endswith('/'):
new_path = request.path_info[:-1]
else:
new_path = request.path_info + '/'
if _is_valid_path(new_path, urlconf):
# if the new url is valid, redirect to it
return http.HttpResponsePermanentRedirect(generate_url(request, new_path))
3
View Complete Implementation : middleware.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : unt-libraries
Copyright BSD 3-Clause "New" or "Revised" License
Author : unt-libraries
def process_response(self, request, response):
"""If a 404 is raised within a view, try appending/removing the slash (based
on the `APPEND_SLASH` setting) and redirecting if the new url is valid."""
if response.status_code == 404:
if not request.path_info.endswith('/') and settings.APPEND_SLASH:
new_path = request.path_info + '/'
elif request.path_info.endswith('/') and not settings.APPEND_SLASH:
new_path = request.path_info[:-1]
else:
new_path = None
if new_path:
urlconf = getattr(request, 'urlconf', None)
if _is_valid_path(new_path, urlconf):
return http.HttpResponsePermanentRedirect(generate_url(request, new_path))
return response
def flatpage(request, url):
"""
Public interface to the flat page view.
Models: `flatpages.flatpages`
Templates: Uses the template defined by the ``template_name`` field,
or :template:`flatpages/default.html` if template_name is not defined.
Context:
flatpage
`flatpages.flatpages` object
"""
if not url.startswith('/'):
url = '/' + url
site_id = get_current_site(request).id
try:
f = get_object_or_404(FlatPage, url=url, sites=site_id)
except Http404:
if not url.endswith('/') and settings.APPEND_SLASH:
url += '/'
f = get_object_or_404(FlatPage, url=url, sites=site_id)
return HttpResponsePermanentRedirect('%s/' % request.path)
else:
raise
return render_flatpage(request, f)
0
View Complete Implementation : link_views.py
Copyright MIT License
Author : creativecommons
Copyright MIT License
Author : creativecommons
@swagger_auto_schema(operation_id="link_resolve",
responses={
200: None,
301: 'Moved Permanently',
404: 'Not Found'
})
def get(self, request, path, format=None):
"""
Given a shortened URL path, such as 'zb3k0', resolve the full URL
and redirect the caller.
"""
try:
link_instance = ShortenedLink.objects.get(shortened_path=path)
except ShortenedLink.DoesNotExist:
return Response(
status=404,
data='Not Found'
)
full_url = link_instance.full_url
return HttpResponsePermanentRedirect(full_url)
0
View Complete Implementation : decorators.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : django-userena-ce
Copyright BSD 3-Clause "New" or "Revised" License
Author : django-userena-ce
def secure_required(view_func):
"""
Decorator to switch an url from http to https.
If a view is accessed through http and this decorator is applied to that
view, than it will return a permanent redirect to the secure (https)
version of the same view.
The decorator also must check that ``USERENA_USE_HTTPS`` is enabled. If
disabled, it should not redirect to https because the project doesn't
support it.
"""
def _wrapped_view(request, *args, **kwargs):
if not request.is_secure():
if getattr(
settings,
"USERENA_USE_HTTPS",
userena_settings.DEFAULT_USERENA_USE_HTTPS,
):
request_url = request.build_absolute_uri(request.get_full_path())
secure_url = request_url.replace("http://", "https://")
return HttpResponsePermanentRedirect(secure_url)
return view_func(request, *args, **kwargs)
return wraps(view_func, astigned=WRAPPER_astIGNMENTS)(_wrapped_view)
def flatpage(request, url):
"""
Public interface to the flat page view.
Models: `flatpages.flatpages`
Templates: Uses the template defined by the ``template_name`` field,
or :template:`flatpages/default.html` if template_name is not defined.
Context:
flatpage
`flatpages.flatpages` object
"""
if not url.startswith('/'):
url = '/' + url
site_id = get_current_site(request).id
try:
f = get_object_or_404(FlatPage,
url=url, sites=site_id)
except Http404:
if not url.endswith('/') and settings.APPEND_SLASH:
url += '/'
f = get_object_or_404(FlatPage,
url=url, sites=site_id)
return HttpResponsePermanentRedirect('%s/' % request.path)
else:
raise
return render_flatpage(request, f)
def flatpage(request, url):
"""
Public interface to the flat page view.
Models: `flatpages.flatpages`
Templates: Uses the template defined by the ``template_name`` field,
or :template:`flatpages/default.html` if template_name is not defined.
Context:
flatpage
`flatpages.flatpages` object
"""
if not url.startswith('/'):
url = '/' + url
site_id = get_current_site(request).id
try:
f = get_object_or_404(FlatPage,
url__exact=url, sites__id__exact=site_id)
except Http404:
if not url.endswith('/') and settings.APPEND_SLASH:
url += '/'
f = get_object_or_404(FlatPage,
url__exact=url, sites__id__exact=site_id)
return HttpResponsePermanentRedirect('%s/' % request.path)
else:
raise
return render_flatpage(request, f)
def login(request):
if request.method == 'POST':
url = request.POST.get("url", None)
pwd = request.POST.get("pwd", None)
else:
if request.session.get('url') == None:
return HttpResponsePermanentRedirect("/")
else:
url = request.session.get("url")
pwd = request.session.get("pwd")
s = SendCode(url=url, pwd=pwd)
path = request.session.get("now_path")
if not path:
path = s.getFilePath()
# path = s.getFilePath()
filelist = s.getFilelist(path)
filelist = formatsize(filelist)
path_list = path.split("/")
if path_list[0] == '':
print('*'*30)
path_list[0] = '/'
# 设置path_sesion 记录用户当前访问的路径
request.session['now_path'] = path
request.session['url'] = url
request.session['pwd'] = pwd
return render(request, 'nife/html/workbench.html',
context={"files": filelist, "path_list": path_list, "url": url, "pwd": pwd})
0
View Complete Implementation : views.py
Copyright GNU General Public License v2.0
Author : kiwitcms
Copyright GNU General Public License v2.0
Author : kiwitcms
def get(self, request, *args, **kwargs):
test_plan = self.get_object()
return HttpResponsePermanentRedirect(reverse('test_plan_url',
args=[test_plan.pk,
slugify(test_plan.name)]))
0
View Complete Implementation : views.py
Copyright GNU General Public License v3.0
Author : Liweimin0512
Copyright GNU General Public License v3.0
Author : Liweimin0512
def get(self, request):
logout(request)
# 重定向
return HttpResponsePermanentRedirect(reverse('login'))
def redirect_original(request, short_id):
url = get_object_or_404(urls, pk=short_id) # get object, if not found return 404 error
url.count += 1
url.save()
return HttpResponsePermanentRedirect(url.httpurl)
def redirect(self, rendition):
# Redirect to the file's public location
return HttpResponsePermanentRedirect(rendition.url)
def static_redirect(request):
return HttpResponsePermanentRedirect(
"http://static.simonwillison.net%s" % request.get_full_path()
)
def tag_redirect(request, tag):
return HttpResponsePermanentRedirect("/tags/{}/".format(tag))
0
View Complete Implementation : middleware.py
Copyright Apache License 2.0
Author : simonw
Copyright Apache License 2.0
Author : simonw
def redirect_middleware(get_response):
def middleware(request):
path = request.path.lstrip('/')
redirects = list(Redirect.objects.filter(
domain=request.get_host(),
# We redirect on either a path match or a '*'
# record existing for this domain
path__in=(path, '*')
))
# A non-star redirect always takes precedence
non_star = [r for r in redirects if r.path != '*']
if non_star:
return HttpResponsePermanentRedirect(non_star[0].target)
# If there's a star redirect, build path and redirect to that
star = [r for r in redirects if r.path == '*']
if star:
new_url = star[0].target + path
if request.META['QUERY_STRING']:
new_url += '?' + request.META['QUERY_STRING']
return HttpResponsePermanentRedirect(new_url)
# Default: no redirects, just get on with it:
return get_response(request)
return middleware
0
View Complete Implementation : categories.py
Copyright MIT License
Author : tramcar
Copyright MIT License
Author : tramcar
def categories_show(request, category_id, slug=None):
category = get_object_or_404(
Category,
pk=category_id,
site_id=get_current_site(request).id
)
if slug is None:
return HttpResponsePermanentRedirect(category.get_absolute_url())
jobs = Job.objects.filter(site_id=get_current_site(request).id) \
.filter(category_id=category_id) \
.filter(paid_at__isnull=False) \
.filter(expired_at__isnull=True) \
.order_by('-paid_at')
form = SubscribeForm()
meta_desc = 'Browse a list of all active %s jobs' % category.name
feed_url = reverse('categories_feed', args=(category.id, category.slug(),))
satle = '%s Jobs' % category.name
context = {'meta_desc': meta_desc,
'link_rss': feed_url,
'satle': satle,
'form': form,
'jobs': jobs}
return render(request, 'job_board/jobs_index.html', context)
0
View Complete Implementation : companies.py
Copyright MIT License
Author : tramcar
Copyright MIT License
Author : tramcar
def companies_show(request, company_id, slug=None):
company = get_object_or_404(
Company,
pk=company_id,
site_id=get_current_site(request).id
)
if slug is None:
return HttpResponsePermanentRedirect(company.get_absolute_url())
# We don't use get_list_or_404 here as we redirect to this view after
# adding a new company and at that point it won't have any jobs astigned
# to it.
jobs = Job.objects.filter(site_id=get_current_site(request).id) \
.filter(company=company) \
.filter(paid_at__isnull=False) \
.order_by('-paid_at')
satle = company.name
meta_desc = 'Browse a list of all active and expired %s jobs' % \
company.name
context = {'meta_desc': meta_desc,
'satle': satle,
'company': company,
'jobs': jobs}
return render(request, 'job_board/companies_show.html', context)
def jobs_show(request, job_id, slug=None):
job = get_object_or_404(
Job, pk=job_id, site_id=get_current_site(request).id
)
if slug is None:
return HttpResponsePermanentRedirect(job.get_absolute_url())
site = get_current_site(request)
# If the browsing user does not own the job, and the job has yet to be paid
# for, then 404
if (job.user.id != request.user.id and not request.user.is_staff and
job.paid_at is None):
raise Http404("No Job matches the given query.")
# If someone views an unpaid job (job owner or admin), display the job's
# created_at date instead of paid_at
if job.paid_at is None:
post_date = job.created_at
else:
post_date = job.paid_at
md = markdown.Markdown(safe_mode='remove')
job.description_md = md.convert(job.description)
job.application_info_md = md.convert(job.application_info)
job.remote = "Yes" if job.remote else "No"
if job.remote == "Yes":
meta_desc = '%s is hiring a remote %s. Apply today!' % \
(job.company.name, job.satle)
else:
meta_desc = '%s is hiring a %s in %s, %s. Apply today!' % \
(job.company.name, job.satle, job.city, job.state)
satle = "%s @ %s" % (job.satle, job.company.name)
stripe_key = site.siteconfig.stripe_publishable_key
tokens = 0
if hasattr(job.user, 'usertoken'):
if job.user.usertoken.tokens > 0:
tokens = job.user.usertoken.tokens
context = {'job': job,
'post_date': post_date,
'meta_desc': meta_desc,
'satle': satle,
'remote': site.siteconfig.remote,
'stripe_publishable_key': stripe_key,
'price': site.siteconfig.price,
'price_in_cents': site.siteconfig.price_in_cents(),
'tokens': tokens}
return render(request, 'job_board/jobs_show.html', context)