How do I make a POST request to flask? - python

I'm new to Flask and I'm trying to find a way to invoke the elif statement in the code below, without having to manually type in the url when I run my app. In other words, I'd like to be able to provide a url in one of my templates that will make a POST request for question(title). Can anyone give me insight?
#application.route('/question/<title>', methods=['GET', 'POST'])
def question(title):
if request.method == 'GET':
question = r.get(title+':question')
return render_template('AnswerQuestion.html',
question = question)
elif request.method == 'POST':
submittedAnswer = request.form['submittedAnswer'];
answer=r.get(title+':answer')
if submittedAnswer == answer:
return render_template('Correct.html');
else:
return render_template('Incorrect.html',
answer = answer,
submittedAnswer = submittedAnswer);

Looks like in thePOST request, you are getting the contents of a form. You can try to create a form whose action="/question/some_title" and method="post". So on submit this will be handled on theelif part of your flask code.
Or you can try sending am ajax request through JavaScript or jQuery, with relevant data, method and URL.

Related

How to redirect to page where request came from in Django

I currently work on a project an i want to redirect to page where request is came form, when request method is GET.
this is my views.py file
Views.py
def delete_patient(request):
if request.method == 'POST':
patient_id = request.POST['patient_id']
rem = Patient.objects.get(pk=patient_id)
rem2 = CustomUser.objects.get(aid=patient_id, role=4)
rem.delete()
rem2.delete()
return JsonResponse({'delete': 1})
else:
// //
so please tell me what I want to write in else part of view.
Typically for that, the server responds with a 405 method not allowed. Especially since it is not even said that the request "comes from somewhere". For example one can make such request with curl, wget, etc. You can work with a #require_POST decorator [Django-doc] for example to return a 405 in case the method is something else than a POST (GET, PUT, PATCH, etc.):
from django.views.decorators.http import require_POST
#require_POST
def delete_patient(request):
patient_id = request.POST['patient_id']
rem = Patient.objects.get(pk=patient_id)
rem2 = CustomUser.objects.get(aid=patient_id, role=4)
rem.delete()
rem2.delete()
return JsonResponse({'delete': 1})
If you really want to redirect to the referring page, you can try to access the HTTP_REFERER key from the request.META dictionary. But not all browsers per se send the referring page, and it is not even said that the request comes from a web client in the first place.
You thus can work with:
from django.http import HttpResponseNotAllowed, HttpResponseRedirect
def delete_patient(request):
if request.method == 'POST':
patient_id = request.POST['patient_id']
rem = Patient.objects.get(pk=patient_id)
rem2 = CustomUser.objects.get(aid=patient_id, role=4)
rem.delete()
rem2.delete()
return JsonResponse({'delete': 1})
elif 'HTTP_REFERER' in request.META:
return HttpResponseRedirect(request.META['HTTP_REFERER'])
else:
return HttpResponseNotAllowed(['POST'])

Python Flask: Creating redirect to another website function

I have this problem, where I try to redirect to another URL using FLASK. My HTML form uses POST to get the input to backend:
if request.method == 'POST' and 'redirectButton' in request.form:
createRedirect(request.form['redirectButton'])
And then using my createRedirect func. I would like to redirect them, to URL I have assembled:
def createRedirect(videoName):
redirectLink = "https://www.youtube.com/watch?v={}".format(VIDEOID[videoname])
print(redirectLink)
return redirect(redirectLink, code=302)
If I click on the printed link, new tab opens on my explorer and it works fine, but the redirect does not happen -> the URL is right
Also I have no problem with formatting
How about
if request.method == 'POST' and 'redirectButton' in request.form:
redirect_data = createRedirect(request.form['redirectButton']
return redirect(redirect_data["link"], code=redirect_data["code"])
def createRedirect(videoName):
redirectLink = "https://www.youtube.com/watch?v={}".format(VIDEOID[videoname])
print(redirectLink)
return {"link": redirectLink, "code": 302}
I think you have to return the redirect.
#app.route('/')
def hello():
return redirect(redirectLink, code=302)

flowjs to upload files POST request sends empty array

I'm trying to use flowjs/ng-flow to upload images but I'm not getting anything on my backend.
This is the method that is supposed to receive the images in my Flask routes.py:
#app.route('/api/file/upload/', methods = ['GET', 'POST'])
#login_required
def upload_files():
if request.method == 'GET':
print "GET"
print request.args
else:
print "POST"
print request.args
return "200"
Before finding out that I had to set testChunks:false, I was receiving only a GET request and request.args looked like this:
ImmutableMultiDict([('flowFilename', u'coldplay_butterfly.JPG'), ('flowTotalChunks', u'1'), ('flowRelativePath', u'coldplay_butterfly.JPG'), ('flowTotalSize', u'35338'), ('flowCurrentChunkSize', u'35338'), ('flowIdentifier', u'35338-coldplay_butterflyJPG'), ('flowChunkSize', u'1048576'), ('flowChunkNumber', u'1')])
As for the POST, I get this:
ImmutableMultiDict([])
I have no idea why this is happening. I could also use some help on what to do after I get the array with the files, as in how to properly save the images to a folder inside my project. The only example I found was in PHP, so if someone could clarify how to do that in Python I would really appreciate it!
Thanks!

Flask login_required + next url params

I have a protected view in my app which just accepts POST requests.
#app.route("/booking", methods=("POST", ))
#login_required
def booking():
arg1 = request.form.get("arg1")
arg2 = request.form.get("arg2")
When an unauthorized user tries to access this view, I want them to
login and then be redirected here.
Right now, my login view looks like this:
#app.route("/login", methods=("GET", "POST"))
#login_required
def login():
do_login()
return redirect(request.args.get('next') or url_for('home'))
So what ends up happening is a POST request to /booking (which is the
"next" parameter) and I get a NOT ALLOWED error.
The problem is that login() makes a GET request to booking(). I can
get around that, but I am not sure how to retrieve the original POST
form arguments from /booking? Any ideas to get round that?
I would solve this by pulling the data and putting it in the session. You can remove the #login_required decorator and check this in the function using current_user.is_authorized. See Flask Sessions and Flask Login.
Something like this might work for you, I didn't test it:
from flask import session
from flask_login import current_user
#app.route("/booking", methods=("POST", ))
def booking():
if not 'arg1' in session.keys() and not 'arg2' in session.keys():
session['arg1'] = request.form.get("arg1")
session['arg2'] = request.form.get("arg2")
# Now the data will persist in the session
if current_user.is_authorized:
# Do what you need...
else:
# Redirect to login, session will persist
Why would you only use POST in the booking view ? You are probably rendering a form which should also allow GET.
#app.route("/booking", methods=['GET','POST'])
#login_required
def booking():
# render the form. something like
form = BookingForm()
# Check if POST
if request.method == 'POST':
# process the form now and do whatever you need.
return redirect(url_for('index'))
# code below will run if not POST. You should render the template here
return render_templte('booking.html')

Django controller to require method

I read the following page:
https://docs.djangoproject.com/en/1.2/topics/http/decorators/
Basically, I have a function in a controller that only accepts POST requests. And the documentation on that page allowed me to do that. However, i'm noticing that when the user sends a GET or PUT etc, the response is literally nothing. How can I send a generic error or a 404 page or something?
It doesn't return nothing. It returns a 405 Method Not Allowed HTTP status code. This indicates to the client that the requested method is not allowed (as the name describes).
If you're dead set on returning something else, just don't use the decorator. All it does is test if the requested method is in the allowed list of methods. Just add the following to your view code and you can do whatever you want for each condition:
if request.method in ['GET', 'POST']:
// allowed
else:
// not allowed
I can't remember if it was request.method or not and I don't have Django currently installed on any machines to double-check, but something like this could work.
#require_http_methods(["GET", "POST"])
def my_view(request):
if request.method == 'GET':
# return a 404 or something
# or
if request.method != 'POST':
# return a 404 or something
But shouldn't you be getting your generic 405 - Method not allowed return page if you've only allowed POST for eg. to a certain controller ?
Try this =) Good luck!
from django.http import HttpResponseNotAllowed
def my_view(request):
if request.method != 'POST':
return HttpResponseNotAllowed(permitted_methods=('POST',))

Categories

Resources