【问题标题】:How to enqueue a function with an argument with Redis Queue?如何使用 Redis Queue 将带有参数的函数排入队列?
【发布时间】:2021-05-24 09:09:52
【问题描述】:

我想将一个函数排入队列以在后台运行(使用 Redis 队列)并在函数完成后向客户端发送消息,所以我在后台任务完成后使用 send(msg) 使用 Flask SocketIO。代码在这里

# Server

@app.route("/update")
def update():
  job = q.enqueue(updateFiles) # Send function to background
  return render_template("index.html")

@socketio.on("message")
def updateFiles(msg): # Function running on background
  time.sleep(5)
  send(msg) # Sending message to the client after executing functions updateFiles

# HTML (jQuery):

socket.emit("message", "Files updated successfully"); // Emitting message to server
socket.on('message', function (msg) { // Receive message from server and show it on HTML template
  $("#message").html(msg);
});

在服务器(Heroku)上有这个错误:

2021-02-22T05:12:00.810166+00:00 app[worker.1]:   File "/app/.heroku/python/lib/python3.6/site-packages/rq/job.py", line 719, in _execute
2021-02-22T05:12:00.810172+00:00 app[worker.1]:     return self.func(*self.args, **self.kwargs)
2021-02-22T05:12:00.810172+00:00 app[worker.1]: TypeError: actualizarExpedientes() missing 1 required positional argument: 'msg'

我发现问题出在job = q.enqueue(updateFiles),因为 updateFiles 需要一个参数。问题是参数msg 来自SocketIO,在使用jQuery 自动发出消息之后。如何解决这个问题?

【问题讨论】:

    标签: python redis flask-socketio


    【解决方案1】:

    来自rq docs

    q = Queue('low', connection=redis_conn)
    q.enqueue(count_words_at_url,
              ttl=30,  # This ttl will be used by RQ
              args=('http://nvie.com',),
              kwargs={
                  'description': 'Function description', # This is passed on to count_words_at_url
                  'ttl': 15  # This is passed on to count_words_at_url function
              })
    
    

    当您调用 q.enqueue 时,只需将您的参数作为第二个参数放入

     job = q.enqueue(updateFiles, msg)
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多