如何在grpc中管理数据库连接?

2024-04-26 04:23:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在grpc中学习一些快速入门教程,其中添加了一些数据库连接,显然,在每个请求中创建数据库连接并不是最优的

def connection():
    conn = psycopg2.connect(
        user="postgres", password="some_password", database="some_db")
    return conn


class LeagueGameManager(start_pb2_grpc.GameManagerServicer):
    async def CreateLGGame(self, request, context):
        try:
            conn = connection()
            cursor = conn.cursor()

            cursor.execute("some sql statement")

            conn.commit()
            cursor.close()
            conn.close()
        except OperationalError as e:
            context.set_details(e)
            context.set_code(grpc.StatusCode.INTERNAL)
            cursor.close()
            conn.close()
            return

        return start_pb2.GameReply(json_response=json.dumps(new_row[0]))


async def serve():
    server = grpc.aio.server()
    start_pb2_grpc.add_GameManagerServicer_to_server(
        LeagueGameManager(), server)
    listen_addr = '[::]:50051'
    server.add_insecure_port(listen_addr)
    logging.info("Starting server on %s", listen_addr)
    await server.start()
    await server.wait_for_termination()

管理上述数据库连接的最佳方式是什么


Tags: 数据库closegrpcreturnserverdefcontextsome
1条回答
网友
1楼 · 发布于 2024-04-26 04:23:34

我知道我有点晚了,但由于python中的gRPC没有很好的文档记录,我想帮助未来的访问者。 我最近一直在和gRPC打交道。对我来说,与数据库保持恒定连接的最简单方法是在服务类的构造函数中连接数据库。在我的例子中,我连接到MongoDb,它应该是这样的:

class MyServiceClass(MyServiceClass_pb2_grpc.MyServiceClassServicer):
    def __init__(self) -> None:
        super().__init__()
        self.client = pymongo.MongoClient(CONNSTRING) # Connection to Mongo database
        self.client.server_info()
    async def get_info(self, request, context):
        response_info = MyScript(request.code).get_something()  # Call 
        return MyServiceClasse_pb2.InfoResponse(info= response_info)
async def serve():
    server = grpc.aio.server()
    start_pb2_grpc.add_MyServiceClass_to_server(
        MyServiceClass(), server)
    listen_addr = '[::]:50051'
    server.add_insecure_port(listen_addr)
    logging.info("Starting server on %s", listen_addr)
    await server.start()
    await server.wait_for_termination()

相关问题 更多 >