Skip to main content
 首页 » 编程设计

python之cassandra 在 uwsgi 服务器中增加操作超时

2024年10月24日15落叶无声

我有一个用 python 编写的 Web 服务器,它使用 Cassandra 的 python 驱动程序与 cassandra 数据库交互。 当我使用 gunicorn http 服务器启动这个 python 服务器时,我的请求得到了无误的处理。 但是当我在第一次请求后使用 uwsgi http 服务器运行同一个服务器时,它必须将一些数据写入 Cassandra 表,cassandra 引发错误

cassandra.OperationTimedOut: errors={}, last_host=127.0.0.1

错误在 python 中的 session.prepare() 函数调用中引发。

请您参考如下方法:

我们在应用程序中收到相同的错误消息。

我们通过在构造函数中打开 Cassandra session ,并在模型类的销毁函数中关闭它来修复它。请看下面的代码

class Model(): 
      def __init__(self): 
          self.db = cassandra.createSession() 
 
      def __del__(self): 
          self.db.shutdown() 

已编辑: 我在这里找到了更好的解决方案:uWSGI Cassandra

from cqlengine import connection 
from cqlengine.connection import ( 
    cluster as cql_cluster, session as cql_session) 
 
try: 
    from uwsgidecorators import postfork 
except ImportError: 
    # We're not in a uWSGI context, no need to hook Cassandra session 
    # initialization to the postfork event. 
    pass 
else: 
    @postfork 
    def cassandra_init(): 
        """ Initialize a new Cassandra session in the context. 
 
        Ensures that a new session is returned for every new request. 
        """ 
        if cql_cluster is not None: 
            cql_cluster.shutdown() 
        if cql_session is not None: 
            cql_session.shutdown() 
        connection.setup()