Accessing Flask server from my web page

2020-05-03 10:42发布

问题:

This is a question continue from this question here.

I am trying to control a servo motor using the image buttons on my web page. My servo controller is in the form of python script (cameraservo2.py) and I am using jQuery to post the data to the python function. The conclusion that I get from asking "how to run python script from webpage" is by using 'Flask' which is totally new to me. However I have installed it successfully using just pip install Flask. (let me know if i miss out anything?)

I have my index.html, cameraservo3.py and routes.py in my /var/wwwfolder. My webserver is by default running and I can access it by my Raspberry Pi IP address from another network computer.

This is my routes.py code:

from flask import Flask, jsonify, render_template, request
from cameraservo3 import turnCamera

app = Flask(__name__)

@app.route('/turn_servo', methods=['POST'])
def turn_servo_ajax():
    direction = request.form['direction']
    cam_result = turnCamera(direction=direction)
    return '<div> {} </div>'.format(cam_result)   

if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0')

Part of my jQuery script in index.html:

$('#left_button').click(function(){
            $.post("/turn_servo", {direction:"left"}).done(function (reply) {
                $('#camerapos').empty().append(reply);
                alert("left button clicked");});

        });

part of my html:

<div id="control_button">
    <img src="button_left.png" id="left_button" height="50" width="50">
    <img src="button_right.png" id="right_button" height="50" width="50">
    <p id="camerapos"> test </p>
  </div>

cameraservo2.py can be found in the answer for my question there. I run python routes.py and it gave me

 * Running on http://0.0.0.0:5000/
 * Restarting with reloader

But the script (cameraservo2.py) doesn't get executed when I click the left_button. What's wrong? Which part have I done wrong??

The quickstart guide of Flask isn't very helpful as well. :/

回答1:

You'll run into the same-origin policy restrictions unless you serve the index.html file from the same host and port number. It's easiest to just add the index.html page to your Flask server too.

Add a / route that serves the page that will do the AJAX post. You could use a template to fill in the route here for $.post() to. If using Jinja2 for the template, that would be:

@app.route('/')
def homepage():
    return render_template('index.html')

and the file index.html in the templates subdirectory of your Flask project with:

$('#left_button').click(function(){
        $.post("{{ url_for('turn_servo_ajax') }}", {direction:"left"}).done(function (reply) {
            $('#camerapos').empty().append(reply);
            alert("left button clicked");});

    });

where the {{ }} part is Jinja2 template syntax, and url_for() returns a fully-formed URL for the turn_servo_ajax view function.