【问题标题】:Simple Network UDP Listen in Flask or PyramidFlask 或 Pyramid 中的简单网络 UDP 侦听
【发布时间】:2014-12-04 14:11:16
【问题描述】:

我需要创建一个 Web 应用程序来显示通过定期传入的 UDP 数据包提供的数据。该站点可能位于 Flask(可能是 Pyramid)中,部署在 Nginx 下。我如何创建一个非常简单的后台任务(基本上只是 socket.recv())来监听任何传入的数据包,并将数据推送到全局可访问的列表中?

我可以简单地从 main() 生成一个线程来执行此操作,还是需要使用 Celery 或 PyRes 之类的东西?

感谢您的指导。

【问题讨论】:

    标签: python nginx flask wsgi


    【解决方案1】:

    您将不得不使用芹菜,但您很幸运,因为There's already a flask extension that integrates celery。你必须pip install flaskpip install flask-celerypip install redis,并且你的系统上需要一个redis服务器。

    import socket, select, Queue
    
    from flask import Flask
    from celery import Celery
    
    
    def make_celery(app):
        celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'])
        celery.conf.update(app.config)
        TaskBase = celery.Task
        class ContextTask(TaskBase):
            abstract = True
            def __call__(self, *args, **kwargs):
                with app.app_context():
                    return TaskBase.__call__(self, *args, **kwargs)
        celery.Task = ContextTask
        return celery
    
    app = Flask(__name__)
    app.config.update(
        CELERY_BROKER_URL='redis://localhost:6379',
        CELERY_RESULT_BACKEND='redis://localhost:6379'
    )
    celery = make_celery(app)
    socket_queue = Queue.Queue()
    
    
    @celery.task()
    def listen_to_udp():
        """
        This code was taken from 
        https://stackoverflow.com/questions/9969259/python-raw-socket-listening-for-udp-packets-only-half-of-the-packets-received
        """
        s1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s1.bind(('0.0.0.0', 1337))
        s2 = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)
        s2.bind(('0.0.0.0', 1337))
        while True:
            r, w, x = select.select([s1, s2], [], [])
            for i in r:
                socket_queue.put((i, i.recvfrom(131072)))
    
    @app.route("/")
    def test_home():
        listen_to_udp.delay()
        print(socket_queue.get())
    
    if __name__ == "__main__":
        #run install.py to install dependencies and create the database
        app.run(host="0.0.0.0", port=5000, debug=True)
    

    【讨论】:

    猜你喜欢
    • 2018-10-12
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    • 2018-12-04
    • 1970-01-01
    • 2017-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多