我正在尝试编写一个 Flask Web 应用程序(托管在 Heroku 上),它将接受从 Xively 发布到它的数据点。
下面的代码用于获取数据点,对其进行修改(添加 2),然后将其发送回 xively 提要:
import os
from flask import Flask
from flask import request
import xively
app = Flask(__name__)
@app.route('/', methods=['GET','POST'])
def take_xively_post_data():
if request.method == 'POST':
if not request.json or not 'current_value' in request.json:
abort(400)
else:
key = 'f5vezDTq4VphhXyCn......'
feedid = '21094....'
lev = request.json['current_value']
#the following code just adds 2 to the POSTed value and
#sends it back to xively
lev = lev + 2
client1 = xively.Client(key)
datastream = xively.Datastream(id="DatastreamID", current_value= lev)
return client1.put('/v2/feeds/'+feedid, data={'datastreams': [datastream]}
else:
return 'Hello'
但是当 Xively 发布到应用程序的 URL 时,什么也没有发生。 (它应该将修改后的数据发送回 Xively 提要。)
Heroku 日志显示 500 错误:
2014-05-29T14:00:55.844275+00:00 heroku[router]: at=info method=POST path=/ host=....herokuapp.com request_id=... fwd="..." dyno=web.1 connect=1ms service=17ms status=500 bytes=454
我认为代码中存在问题,但不知道它是什么...
我尝试将 client1.put(...) 语句向上移动并且不返回任何内容,如下所示,但同样的事情发生了:
import os
from flask import Flask
from flask import request
import xively
app = Flask(__name__)
@app.route('/', methods=['GET','POST'])
def take_xively_post_data():
if request.method == 'POST':
if not request.json or not 'current_value' in request.json:
abort(400)
else:
key = 'f5vezDTq4VphhXyCn......'
feedid = '21094....'
lev = request.json['current_value']
lev = lev + 2
client1 = xively.Client(key)
datastream = xively.Datastream(id="DatastreamID", current_value= lev)
#moved the client1.put function up and returning nothing
client1.put('/v2/feeds/'+feedid, data={'datastreams': [datastream]}
return
else:
return 'Hello'
我试过 request.form() 而不是 request.json() 但这似乎也不起作用。
如果有人能指出编码错误,我将不胜感激。
最佳答案
不确定您是否解决了您的问题,但我想我可以提供帮助。
您请求当前值的方式很可能不正确。这将导致找不到您的 key ,这肯定会通过 500。
我假设您正在使用 Xively 触发器来发出 POST 请求。如果是这种情况,请从更改 lev = request.json['current_value']
开始。至lev = request.json['triggering_datastream']['value']['value']
.这至少应该为您提供已发送触发器的数据流的实际当前值。
然后当然改变你的return
值(value)类似于 200
没有其他人建议的 body 。
看看这是否有效,然后我们可以尝试调试您发送回 Xively 的 PUT。该代码对我来说看起来很正确。
关于python - 如何在 flask 网络应用程序中接受来自 Xively 的 POST 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23936454/