Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

你好作者 @CoderCharm 我将 mongodb 以及 ws 注册到了 fastapi 组件,我可以 PR 到此吗? #15

Open
PY-GZKY opened this issue May 19, 2021 · 1 comment

Comments

@PY-GZKY
Copy link

PY-GZKY commented May 19, 2021

就像这样

def register_mysql(app: FastAPI):
    # 添加数据库连接和关闭事件
    @app.on_event("startup")
    async def connect_to_mysql():
        await database.connect()
        logger.debug("MYSQL 数据库初始化成功 ... DONE")
        await database.disconnect()

def register_mongodb(app: FastAPI):
    # 添加数据库连接和关闭事件
    @app.on_event("startup")
    async def connect_to_mongo():
        try:
            db.client = AsyncIOMotorClient(settings.MONGODB_URL,
                                           maxPoolSize=settings.MAX_CONNECTIONS_COUNT,
                                           minPoolSize=settings.MIN_CONNECTIONS_COUNT)
            logger.debug("MONGODB 数据库初始化成功 ... DONE")
        except:
            logger.error("MONGODB 数据库初始化失败 ... DONE")

    @app.on_event("shutdown")
    async def close_mongo_connection():
        db.client.close()
        logger.debug("MONGODB 数据库连接关闭 ... DONE")


def register_ws(app: FastAPI):
    @app.websocket("/ws/{taskId}")
    async def websocket_endpoint(websocket: WebSocket, taskId):
        await notifier.connect(websocket)
        try:
            if taskId:
                recent_msgs = query_task_log(taskId)  # 根据 taskId 查询历史日志并传输到页面-代码
                print(recent_msgs)
                for msg in recent_msgs:
                    await websocket.send_json(msg)
            while True:
                data = await websocket.receive_text()
                # await websocket.send_json(data)
                await notifier.push(data)
        except WebSocketDisconnect:
            notifier.remove(websocket)

    @app.on_event("startup")
    async def connect_to_ws():
        await notifier.generator.asend(None)
        logger.debug("WEBSOCKET 连接初始化成功 ... DONE")

看到作者基于 fastapi 官方的开发模板改良,心中甚是激动啊

@wxy2077
Copy link
Owner

wxy2077 commented May 20, 2021

websocket 这个有测试例子吗?因为我没有在项目中使用ws,所以我对这块不熟悉,或者你提交一个,带有ws版的分支。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants