如何在python中传递一个restful查询(ajax-style)的结果

时间:2017-01-25 18:42:27

标签: python ajax rest flask routes

我正在开发一款Restful应用。其中一种方法需要一段时间才能返回,我希望将状态流回状态直到完成。请耐心等待我,因为我不是网络开发人员: - )...这就是我所拥有的:

# this is what I normally use to generate the status.  It works great for
# those cases where the status changes immediately:
def door_status():
    global door
    status = {"door count": door.position }
    return Response(json.dumps(status),  mimetype='application/json')

def generate(door_thread, state):
    while door_thread.current_state == state:
        yield ','.join("good stuff goes here") + '\n'

# This is the endpoint that I am having issues with.  door.close_door()
# returns immediately, but the door takes a while to close.  I'd like to
# continue returning status until the door is completely closed.
@app.route(ROOT + 'close_door', methods=['POST'])
def close_door():
global door
    # the following method returns immediately but it takes a while 
    # for the door to close:
    door.close_door() 
    # until the door is finally closed, return status:
    return Response(generate(door, State.opening), mimetype='application/json')

    # Note that the following return works but it does not show the updated
    # status of the door actually being closed:
    # return door_status(), 201

在相关的应用程序中,我使用以下代码获取REST调用的结果并显示它们:

try:
    rtn = urllib2.urlopen(req, context=ctx)
    data = json.load(rtn)
    pp = pprint.PrettyPrinter()
    pp.format = my_safe_repr
    print "Success:" + str(rtn.code)
    pp.pprint(data)
except urllib2.HTTPError as err:
    print str(err) + ":"
    print err.read()

欢迎任何建议。

0 个答案:

没有答案