Flask Redis Queue(RQ)worker无法导入名为app的模块

ejk8hzay  于 2023-05-16  发布在  Redis
关注(0)|答案(5)|浏览(166)

我运行了一个名为modeling-manager的flask应用程序,它从另一个flask应用程序接收post请求。在那之前一切正常(所有文件都位于同一文件夹中)
当被post请求触发时,Modeling-manager在Redis中注册一个job,由worker执行。要执行的作业称为run_model(),它存储在www.example.com(flask应用程序)中的另一个文件和导入main.py。
worker在与modeling-manager应用相同的docker上启动。使用脚本:worker.py

  • main.py * -> flask app
from flask import Flask, request, jsonify
import logging as lg
from datetime import datetime as dt
import os
import boto3
import redis
import json
from rq import Worker, Queue, Connection
from .model import run_model

app = Flask(__name__)

@app.route('/ModelManager/register',  methods=['POST'])
def register_philjob_to_queue():
    lg.info("triggered register cahce on model manager")
    job_data = request.get_json()
    lg.info("json data " + job_data["InstanceNumber"])
    try:
        with Connection(redis.Redis(host="redis-caching", port="6379")):
            lg.info("adding job to queue")
            q = Queue()
            task = q.enqueue(run_model, job_data)
        response_object = {
            'status': 'pending',
            'data': {
                'task_id': task.get_id()
            }
        }
        return jsonify(response_object), 202
        except Exception as e:
          lg.error(e)
  • 工人.py*
import redis
from rq import Worker, Queue, Connection

conn = redis.Redis(host="redis-caching", port="6379")
listen = ['default']

if __name__ == '__main__':
    with Connection(conn):
        worker = Worker(list(map(Queue, listen)))
        worker.work()

finally model.py

import logging as lg
def run_model(job_data):

    # Run phil on started instance
    try:

        lg.info("executing the model") 
        return 'Model Executed'

    except Exception as e:
        print(e)
        print("RUN_MODEL:")
        lg.error(e)

我从worker得到的错误消息,其中“app”可能指的是我的flask应用程序的根文件夹(名为app):

10:35:15 RQ worker 'rq:worker:7555cdf9c1ad.9' started, version 0.12.0
10:35:15 *** Listening on default...
10:35:15 Cleaning registries for queue: default
10:35:15 default: app.model.run_model({'InstanceNumber': '002365984', 
'CallBackUrl': 'http://blabla.be'}) (5e83d96b-de11-4ddb-9c8f- 
b7b256580bfc)
10:35:15 ModuleNotFoundError: No module named 'app'
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/rq/worker.py", line 
793, in perform_job
    rv = job.perform()
  File "/usr/local/lib/python3.7/site-packages/rq/job.py", line 599, in perform
    self._result = self._execute()
  File "/usr/local/lib/python3.7/site-packages/rq/job.py", line 605, in _execute
return self.func(*self.args, **self.kwargs)
  File "/usr/local/lib/python3.7/site-packages/rq/job.py", line 213, 
in func
return import_attribute(self.func_name)
  File "/usr/local/lib/python3.7/site-packages/rq/utils.py", line 152, in import_attribute
    module = importlib.import_module(module_name)
  File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in 
import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 953, in 
_find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'app'
Traceback (most recent call last):
 File "/usr/local/lib/python3.7/site-packages/rq/worker.py", line 793, in perform_job
rv = job.perform()
 File "/usr/local/lib/python3.7/site-packages/rq/job.py", line 599, in perform
self._result = self._execute()
  File "/usr/local/lib/python3.7/site-packages/rq/job.py", line 605, in _execute
return self.func(*self.args, **self.kwargs)
  File "/usr/local/lib/python3.7/site-packages/rq/job.py", line 213, in func 
return import_attribute(self.func_name)
  File "/usr/local/lib/python3.7/site-packages/rq/utils.py", line 152, in import_attribute
module = importlib.import_module(module_name)
  File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
  ModuleNotFoundError: No module named 'app'   
10:35:15 Moving job to 'failed' queue

这都是在docker容器上执行的,redis在不同的容器上。这两个容器之间的通信工作正常。
flask应用程序在docker上使用命令启动: flask 运行--主机=0.0.0.0 --端口=8081

62lalag4

62lalag41#

我正在运行一个flask应用程序,在这里遇到了同样的问题。上面的解决方案对我不起作用。然而,我的问题与不正确的导入有关。
当在终端上调试windows时,我的redis服务器运行在cygwin中。我刚刚开始我的工人与我的静态项目路径。现在我的输入错误解决了。之前:

rq worker flask-task

之后:

rq worker flask-task --path /mnt/c/Users/<USER>/Desktop/projects/flask_app
e37o9pze

e37o9pze2#

找到了解决方案,问题是由于我使用的模块“模型”(.model)的相对路径,它只能以这种方式工作,因为根目录中的init.py文件。所以我删除了init.py文件,将导入改为

from model import run_model

现在一切正常,函数可以被工人找到并正确执行!

nwsw7zdq

nwsw7zdq3#

如果在www.example.com模块的顶部设置工作目录路径worker.py,它应该可以工作。

import sys
sys.path.insert(0, '/path/to/working/directory/')
y0u0uwnf

y0u0uwnf4#

我也面临着同样的问题。在我的情况下,flask应用程序可以使用pip安装,并且已经安装了旧版本的应用程序,其中没有我试图导入的模块。我删除了旧的模块使用pip卸载命令,现在事情正在工作。
可能是rq worker试图从安装的版本而不是相对路径导入模块。
希望这能帮上忙。

p8ekf7hl

p8ekf7hl5#

我偶然发现了这个(和其他许多页面)寻找相同/非常相似问题的解决方案,最终找到了解决方案。
(Note我正在使用Flask,并将我的应用程序设置为带有蓝图/应用程序工厂的包)
我不得不将我的worker.py文件从应用程序包中移到主根文件夹中(例如:包含run.py、Procfile、.gitignore等)。如果它在应用程序包/模块文件夹中,则无法工作)。

相关问题