【问题标题】:Python: Making a Flask Rest API Asynchronous and Deploying itPython:使 Flask Rest API 异步并部署它
【发布时间】:2016-05-01 23:26:22
【问题描述】:

我有一个 python 服务器,它目前正在跟踪我大学中所有公共汽车的位置,并生成到达特定位置的预测。

现在,我想将一个轻量级 REST API 附加到此服务器,但我一直在运行 intro 问题。

我尝试使用带有以下代码的烧瓶:

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)

问题是我在运行服务器大约半天后遇到了以下错误。请注意,在服务器失败并出现以下错误时,没有向服务器发出任何请求:

ERROR:werkzeug: - - [01/May/2016 09:55:55] 代码 400,消息错误请求语法 ('\x02\xfd\xb1\xc5!')

经过调查,我认为我需要部署到 WSGI 生产服务器。但是我不知道在这种特定方法中它意味着什么,因为 1)烧瓶服务器正在线程化以运行预测应用程序的其余部分,以及 2)我正在使用没有文档使用的类。

任何有关如何使用 apache、gunicorn 或您选择的技术设置 wsgi 文件的帮助将不胜感激。此外,任何关于制作非阻塞 REST API 的更好方法的 cmet 都会有所帮助。

如果您需要任何进一步的说明,请告诉我!

【问题讨论】:

    标签: python rest asynchronous flask


    【解决方案1】:

    不确定这是否能真正解决您的问题,但您可以使用基于协程的 Web 服务器 gevent。他们有一个 WSGI 服务器,如果这就是您所说的需要部署 WSGI 生产服务器的意思,您可以使用它。

    如果您想在您的烧瓶应用程序中实现服务器,只需执行以下操作:

    from gevent.pywsgi import WSGIServer
    app = Flask(__name__) 
    http_server = WSGIServer(('', 5000), app)
    http_server.serve_forever()
    

    总的来说,Gevent 是一个非常强大的工具,通过根据需要发出上下文切换,它可以非常轻松地处理多个客户端。此外,gevent 完全支持烧瓶。

    【讨论】:

    • 这似乎绝对有帮助。你知道是否可以将serve_forever 调用到新线程中吗?
    • 确实可以,通过这样做: http = WSGIServer(('', 5000), app) thread = threading.Thread(target=http.serve_forever) thread.start() 但是,你可能需要此代码才能使其工作: from gevent import monkey monkey.patch_all() 这是由于 gevent 删除了自动猴子补丁,并且错误可能是由于没有猴子补丁引起的。 “错误:无法切换到不同的线程”是错误
    【解决方案2】:

    首先要做的是将异常处理用于处理错误的 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'})
    

    【讨论】:

    • 好的,作为健全性检查补充说,但问题是错误发生在服务器没有收到请求的时候(这使得它更加奇怪)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 2022-12-11
    • 1970-01-01
    • 2018-07-23
    • 1970-01-01
    • 2020-06-16
    相关资源
    最近更新 更多