wxcvbn wxcvbn - 1 year ago 73
HTML Question

Use Flask to run a python script using javascript

I want to run a python script using javascript.

I installed Flask.

this is my html code :

<input type="button" value="tester" onclick="addImage()" />

<p id="result"></p>

function callPy(data1, data2){
type: "POST",
data:{data1: data1, data2:data2},

function callbackFunc(response) {
function addImage(){

And this is my python code :

import csv
from numpy import genfromtxt
from numpy import matrix

from flask import Flask, render_template, redirect, url_for,request
from flask import make_response
app = Flask(__name__)

@app.route('/test', method='POST')
def test():
if request.method == 'POST'
data1 = request.form['data1']
data2 = request.form['data2']
return "ok""
return render_template('watermark.html', message='azerty')

if __name__ == "__main__":
app.run(debug = True)

But I have this error in the console :
jquery.min.js:5 POST http://testFalsk/test 404 (Not Found)

What I have to make?

Answer Source

First, the parameter name for the allowed methods is methods (not method) and it accepts a list with the allowed methods. In this case, it will have only one element.

@app.route('/test', methods=['POST'])

With this, the check for request.method == 'POST' isn't necessary, once this view will only accept this type of requests.

Next, there are some syntax errors in your code: the colon after the if statement and the "ok" return string (three double quotes). Also, you have two returns, which isn't valid. To get dict data (as in the request.form) the get method is recommended. It will return None if the key doesn't exist, in oppose to the current way that will throw an exception.
The corrected method would be as follows:

@app.route('/test', methods=['POST'])
def test():
    data1 = request.form.get('data1')
    data2 = request.form.get('data2')

    return render_template('watermark.html', message='azerty')

Please let me know if you're still having problems or my answer isn't clear nor accurate.

Hope it helps.