背景:
我的网站使用ajax从网络摄像头发送图像,该图像通过神经网络运行,并返回1-5的数字。这是处理此问题的代码,效果很好:
@app.route('/guess', methods=['POST'])
def guess():
global result
if request.method == 'POST':
data = request.get_json()
im = Image.open(BytesIO(base64.b64decode(data[22:])))
#Save image on server
filename = str(datetime.now())+".png"
im.save(filename)
#Run image through neural network
results = live_classify.test(filename)
result = str(max(results,key=results.get))
return redirect('/')
它将重定向到此代码,它将重新呈现页面。它将在此处正确打印结果:
@app.route('/')
def index():
global result
print('Result to be displayed:',result)
return render_template("index.html",result=result)
我用来显示结果的html是<p>{{result}}</p>
以及相关的ajax代码:
var imgdata = canvas.toDataURL('image/png');
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/guess",
traditional: "true",
data: JSON.stringify(imgdata),
dataType: "json"
});
但是这个数字没有更新。如果我重新加载页面,它会显示更新的结果,所以我需要告诉页面重新加载吗?
编辑:
我通过使用此ajax请求使其工作:
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
$.getJSON($SCRIPT_ROOT+"/guess",
{imgdata:imgdata},
function(data) {
document.getElementById("result").innerHTML = 'Result: ' + data.result;
});
这可以在Flask中处理数据:
@app.route('/guess')
def guess():
imgdata = request.args.get('imgdata', 0, type=str)
#Image processing stuff
return jsonify(result=result)
答案 0 :(得分:0)
Python
@app.route('/_stuff', methods= ['GET'])
def stuff():
cpu=round(getCpuLoad())
ram=round(getVmem())
disk=round(getDisk())
return jsonify(cpu=cpu, ram=ram, disk=disk)
Javascript
function update_values() {
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
$.getJSON($SCRIPT_ROOT+"/_stuff",
function(data) {
$("#cpuload").text(data.cpu+" %")
$("#ram").text(data.ram+" %")
$("#disk").text(data.disk+" %")
});
}
project/app/views/request/websockets.py
# -*- coding: utf-8 -*-
# OS Imports
import json
# Local Imports
from app import sockets
from app.functions import get_cpu_load, get_disk_usage, get_vmem
@sockets.route('/_socket_system')
def socket_system(ws):
"""
Returns the system informations, JSON Format
CPU, RAM, and Disk Usage
"""
while True:
message = ws.receive()
if message == "update":
cpu = round(get_cpu_load())
ram = round(get_vmem())
disk = round(get_disk_usage())
ws.send(json.dumps(dict(received=message, cpu=cpu, ram=ram, disk=disk)))
else:
ws.send(json.dumps(dict(received=message)))
project/app/__init__.py
# -*- coding: utf-8 -*-
from flask import Flask
from flask_sockets import Sockets
app = Flask(__name__)
sockets = Sockets(app)
app.config.from_object('config')
from app import views
使用Flask-Websockets使我的生活更加轻松。这是启动器:
launchwithsockets.sh
#!/bin/sh
gunicorn -k flask_sockets.worker app:app
最后,这是客户端代码:
custom.js
The code is a bit too long, so here it is.
请注意,我没有使用socket.io之类的东西,这就是代码很长的原因。此代码还尝试定期重新连接到服务器,并且可以停止尝试通过用户操作重新连接。我使用Messenger Messenger库来通知用户出现问题。当然,这比使用socket.io要复杂一些,但是我非常喜欢对客户端进行编码。