繁体   English   中英

从我的网页访问Flask服务器

[英]Accessing Flask server from my web page

这是一个问题,从这里继续。

我正在尝试使用网页上的图像按钮来控制伺服电机。 我的伺服控制器是python脚本(cameraservo2.py)的形式,我使用jQuery post数据到蟒蛇功能。 我从询问“如何从网页运行python脚本”中得出的结论是使用“ Flask”,这对我来说是全新的。 但是我仅使用pip install Flask成功安装了它。 (让我知道我是否错过任何事情吗?)

我的/var/www文件夹中有index.html, cameraservo3.py and routes.py 默认情况下,我的Web服务器正在运行,并且可以从另一台网络计算机通过Raspberry Pi IP地址访问它。

这是我的routes.py代码:

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')

我的jQuery脚本在index.html中的一部分:

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

        });

我的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。 我运行python routes.py ,它给了我

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

但是,当我单击left_button时,脚本(cameraservo2.py)无法执行。 怎么了? 我做错了哪一部分?

Flask的快速入门指南也不是很有帮助。 :/

除非您从相同的主机和端口号提供index.html文件,否则您将遇到同源策略限制。 只需将index.html页面添加到Flask服务器也是最简单的。

添加/路线,以提供将要发布AJAX帖子的页面。 您可以使用模板在此处填写$.post()的路由。 如果使用Jinja2作为模板,则将是:

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

以及Flask项目的templates子目录中的文件index.html ,其中包含:

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

    });

{{ }}部分是Jinja2模板语法,而url_for()返回turn_servo_ajax视图函数的完整URL。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM