[英]Twilio REST API: making calls with android and python / flask
[英]Python: Making a Flask Rest API Asynchronous and Deploying it
我有一個python服務器,當前正在跟蹤我大學中所有公交車的位置,並生成到達特定位置的預測。
現在,我想將輕量級的REST API附加到此服務器,但是我一直在運行介紹問題。
我嘗試將燒瓶與以下代碼結合使用:
from flask import Flask, jsonify
from PredictionWrapper import *
import threading
class RequestHandler():
def __init__(self,predictionWrapper):
self.app = Flask(__name__)
self.predictor = predictionWrapper
self.app.debug = False
self.app.add_url_rule('/<route>/<int:busStop>','getSinglePrediction',self.getSinglePrediction)
t = threading.Thread(target=self.app.run, kwargs={'host':'0.0.0.0', 'port':80, 'threaded':True})
t.start()
def getSinglePrediction(self, route, busStop):
# TODO Get the actual prediction with given parameters
prediction = self.predictor.getPredictionForStop(route, busStop)
return jsonify({'busStop': busStop, 'prediction': prediction})
def getStopPrediction(self, busStop):
# TODO Get the actual prediction with given parameters
return jsonify({'busStop': busStop, 'prediction': 2})
def run(self):
self.app.run(host='0.0.0.0', port=80, threaded=True)
問題是運行服務器大約半天后,我一直遇到以下錯誤。 請注意,在服務器出現以下錯誤時,未向服務器發出任何請求:
錯誤:werkzeug:-[[2016年5月1日09:55:55]代碼400,消息錯誤的請求語法('\\ x02 \\ xfd \\ xb1 \\ xc5!')
經過調查,我相信我需要部署到WSGI生產服務器。 但是我不知道這種特定方法的含義,因為1)正在對燒瓶服務器進行線程化以運行其余的預測應用程序,以及2)我使用的是文檔未使用的類。
對於如何使用apache,gunicorn或您選擇的技術來設置wsgi文件的任何幫助,將不勝感激。 此外,對制作無阻塞REST API的更好方法的任何評論都將有所幫助。
讓我知道您是否需要進一步的澄清!
不知道這是否可以真正解決您的問題,但是您可以使用基於協程的Web服務器gevent。 如果您是說需要部署WSGI生產服務器,那么這就是您可以使用的WSGI服務器。
如果要對Flask應用程序實現服務器,請執行以下操作:
from gevent.pywsgi import WSGIServer
app = Flask(__name__)
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()
Gevent通常是一個非常強大的工具,通過根據需要發出上下文切換,它可以非常輕松地處理多個客戶端。 此外,gevent完全支持flask。
首先要做的是放置異常處理來處理錯誤的JSON請求數據(可能正在發生),例如
def getSinglePrediction(self, route, busStop):
try:
prediction = self.predictor.getPredictionForStop(route, busStop)
return jsonify({'busStop': busStop, 'prediction': prediction})
except:
return jsonify({'busStop': 'error', 'prediction': 'error'})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.