I am completely confused by the following behaviour in Flask. I am sure there is something basic going on but I don't know if this is a script or a server issue, so I posted the shortest example I could come up with.
The page has two ways to post data to the server. One is triggered by submitting a <form>
and the other by a script that listens for Ctrl+V
. I believe both should lead to the last render_template
call. But only the first one does.
paste.html
{%if msg %}
{{ msg }}
{% else %}
Waiting
{% endif %}
<form action="/pastetest" method="post">
Dummy<br>
<input type="text" name="foo" value="bar">
<br>
<input type="submit" value="Send info" />
</form>
Script Listens for a 'paste' event (Ctrl V) and posts some dummy string in a form.
document.addEventListener('paste', function (e) {sendform(e);},false);
sendform = function (e) {
var fd = new FormData();
fd.append('data','testing paste');
var request = new XMLHttpRequest();
request.open("POST", "/pastetest");
request.send(fd);
console.log("Sent")
};
Flask python:
@app.route('/')
def index():
return render_template('paste.html',msg="Waiting")
@app.route('/pastetest',methods=['POST'])
def image_upload():
if request.method == 'POST':
print("On the server")
print(request.form)
alldone="All done time=%d" % time.time()
print(alldone)
return redirect(url_for('confirm',msg=alldone))
@app.route('/confirm/<msg>')
def confirm(msg):
print("At confirm",msg)
return render_template("paste.html",msg=msg) #<---should end up here
From the console I see that the data is being posted and confirm
is being called.
127.0.0.1 - - [19/Nov/2017 00:51:42] "GET /confirm/All%20done%20time%3D1511049102 HTTP/1.1" 200 -
but the page only renders after the submit button. Otherwise it is stuck on Waiting
.
Edit: To clarify: all I need is to get the posted data (just a dummy string above but will be a blob from the clipboard), do something with it and then render a template with the results. What is the easiest way to do this?
(I'm totally ignorant about js/client-server etc. Just trying to make a simple web interface for a image-analysis program that I already wrote. Simple explanations appreciated :)