从我的网页访问Flask服务器 [英] Accessing Flask server from my web page

查看:167
本文介绍了从我的网页访问Flask服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题继续从这个问题这里



我试图用我的网页上的图像按钮来控制伺服电机。我的伺服控制器的形式是python脚本(cameraservo2.py),我使用jQuery到 post 数据到python函数。我从问如何从网页运行python脚本得出的结论是使用Flask,这对我来说是全新的。不过,我已经使用 pip install Flask 成功安装了它。 (让我知道如果我错过了什么?)



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



这是我的 routes.py 代码:

 

















$ b $方向= request.form ['direction']
cam_result = turnCamera(方向=方向)
return'< div> {}< / div>'format(cam_result)

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

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

$ b $点击(功能(){
$ .post(/ turn_servo,{方向:左 })。done(function(reply){
$('#camerapos')。empty()。append(reply);
alert(left button click);});

});

部分我的html:

 < div id =control_button> 
< img src =button_left.pngid =left_buttonheight =50width =50>
< img src =button_right.pngid =right_buttonheight =50width =50>
< p id =camerapos>测试< / p>
< / div>

cameraservo2.py可以在我的问题在那里。我运行 python routes.py ,它给了我

  *正在运行http://0.0.0.0:5000/ 
*重新启动

但脚本(cameraservo2.py)没有得到执行,当我点击left_button。怎么了?哪部分我做错了?

Flask的快速入门指南也不是很有帮助。 : Same-origin_policyrel =nofollow>同源策略限制,除非您从相同的主机和端口号提供 index.html 文件。添加 index.html 页面到你的Flask服务器也是最简单的。



添加一个 / 路由服务于将执行AJAX帖子的页面。你可以使用一个模板来填充 $。post()到的路径。如果使用Jinja2作为模板,那将是:

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

和文件<$在你的Flask项目的 templates 子目录中使用 index.html

< ()函数(){
$ .post({{url_for('turn_servo_ajax')} (#camerapos')。empty()。append(reply);
alert(左键单击);});

});

其中 {{}} 部分是Jinja2模板语法和 url_for() turn_servo_ajax 视图函数返回一个完整的URL。


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. :/

解决方案

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.

这篇关于从我的网页访问Flask服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆