I want to make a redirect and keep what is the query string. Something like self.redirect
plus the query parameters that was sent. Is that possible?
How to make a redirect and keep the query string?
Asked Answered
Where do you want to keep it? In a session? –
Vinson
Can't I just pass on the query parameters via HTTP GET? –
Infarct
Of course, I don't know which framework you are using, but that should be straightforward. In straight http you would send a 301 or 303 with the Location header set to the redirect url plus the query params you want to keep. –
Vinson
Yes, that's what I want to do and I think it is straightforward. I use webapp2 and google app engine, I'm adding those tags to the question. –
Infarct
@Wooble I could try the parameters one by one but I'm looking for a way to add the entire query string in a oneliner. I know the names of the parameters I want to get via HTTP GET and I want to pass on their values. I figure there should be a way to pass on the entire map instead of one variable at a time. –
Infarct
newurl = '/my/new/route?' + urllib.urlencode(self.request.params)
self.redirect(newurl)
can not run in tornado 4 –
Giacinta
Can use
urllib.parse.urlencode(self.request.query_arguments, doseq=True)
in then new version. –
Counterblow You can fetch the query string to the current request with self.request.query_string
; thus you can redirect to a new URL with self.redirect('/new/url?' + self.request.query_string)
.
can not run in tornado 4 –
Giacinta
Use the RedirectView
.
from django.views.generic.base import RedirectView
path('go-to-django/', RedirectView.as_view(url='https://djangoproject.com', query_string=True), name='go-to-django')
This worked for me in Django 2.2. The query string is available as a QueryDict instance request.GET
for an HTTP GET and request.POST
for an HTTP POST. Convert these to normal dictionaries and then use urlencode
.
from django.utils.http import urlencode
query_string = urlencode(request.GET.dict()) # or request.GET.urlencode()
new_url = '/my/new/route' + '?' + query_string
See https://docs.djangoproject.com/en/2.2/ref/request-response/.
© 2022 - 2024 — McMap. All rights reserved.