在flask rest plus中使用restful接口来链接额外的coroutines?

问题描述 投票:0回答:1

是否可以将coroutines与flask restful接口集成在一起?我正在尝试订阅网络套接字,将数据拉到一起。然后,这些数据应该可以通过 restful 接口访问。

但我不确定如何将访问websockets的订阅和处理restful接口本身的事件循环链在一起。 如果有任何建议可以实现,我将非常感激。

python rest websocket python-asyncio flask-restful
1个回答
0
投票

这里有一个我认为可能可行的答案。也许有更好的想法?

import asyncio
from threading import Thread

from flask import Flask
from flask_restplus import Api, Resource

app = Flask(__name__)
api = Api(app, version='1.0', title='Sample API',
          description='A sample API',)


@api.route('/my-resource/', endpoint='my-resource')
class MyResource(Resource):
    def get(self):
        return {"response": cr.i}


def enable_coroutines():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    try:
        asyncio.ensure_future(cr.counter1())
        asyncio.ensure_future(cr.counter2())

        loop.run_forever()
    finally:
        loop.close()


class Coroutines:
    def __init__(self):
        self.i = 0
        self.j = 9

    async def counter1(self):
        i = 0
        while True:
            self.i += 1
            await asyncio.sleep(1)
            print("My Coroutine")
            print(self.i)

    async def counter2(self):
        while True:
            self.j += 1
            await asyncio.sleep(1)
            print(self.j)


if __name__ == '__main__':
    cr = Coroutines()
    coroutines_thread = Thread(target=enable_coroutines, daemon=True)
    coroutines_thread.start()
    app.run(debug=True)
© www.soinside.com 2019 - 2024. All rights reserved.