Flask能与jQuery的post一起使用吗?
我刚接触Flask,在继续之前,我想知道是否可以通过jQuery向Python函数发送“post”请求,使用Flask和JSON?我对JSON也不太了解,所以那些代码对我来说看起来很复杂。
比如说这个例子:
from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
@app.route('/_add_numbers')
我该怎么确定要替换/_add_numbers
这个部分呢?我找不到一个好的网站来给我提供简单的教程或者步骤,教我怎么用Flask做post
请求。
这是我现在的jQuery函数:
$('#left_button').click(function(){
$.post("cameraservo2.py", {direction:"left"}).done(function (reply) {
$('#camerapos').empty().append(reply);
alert("left button clicked");});
});
我可以不使用JSON来做到这一点吗?
2 个回答
1
我把你在原问题中的代码复制过来,来演示一下上面那个回答(Martijns)是怎么和你的代码一起工作的。
# Save this file as app.py
from flask import Flask, jsonify, render_template, request
from cameraservo2 import your_cam_function
app = Flask(__name__)
@app.route('/turn_servo', methods=['POST'])
def turn_servo_ajax():
direction = request.form['direction']
cam_result = your_cam_function(direction=direction)
return '<div> {} </div>'.format(cam_result)
if __name__ == '__main__':
app.run(debug=True)
# This code is in cameraservo2.py and is imported above.
# I've simplified it to a function (not a member of a class).
# You have to work out how to use it in your context.
def your_cam_function(**data):
import pigpio
import time
servos=4
key = data['direction']
m=1500
while (m >= 500 and m <= 2500):
if (key =="left"):
m=m+100
elif (key =="right"):
m=m-100
pigpio.start()
pigpio.set_servo_pulsewidth(servos, m)
servostatus= "Servo {} {} micro pulses".format(servos[0], key, m)
print servostatus
time.sleep(1)
pigpio.stop()
return servostatus
现在,当你向/turn_servo
发送一个POST
请求,并且给它一个direction: left
的参数时,它就会调用你在cameraservo2.py
里的一个函数。这个turn_servo_ajax
函数会返回一段HTML给用户,内容是<div>Servo x y micro pulses</div>
。
4
$.post()
这个方法并不 使用 JSON 格式。它发送的是一个普通的 POST 请求,内容类型是 application/x-www-form-urlencoded
。在 Flask 的路由中,这意味着你发送的字段会在 request.form
对象中找到。如果你的视图返回的是 HTML,你可以把它插入到你的 HTML 文档里。
只需要选择一个能反映你想做的事情的路由名称:
@app.route('/turn_servo', methods=['POST'])
def turn_servo_ajax():
direction = request.form['direction']
# do something with the direction value; it is a string
if direction == 'left':
# ...
else:
# ...
return '<div>Turned the servo 50 degrees to the {}</div>'.format(direction)
然后在你的 $.post
中使用这个路由名称:
$('#left_button').click(function(){
$.post("/turn_servo", {direction:"left"}).done(function (reply) {
$('#camerapos').empty().append(reply);
alert("left button clicked");});
});