我希望启动一个在容器内消费RabbitMQ消息的脚本,以下是重要细节:
messenger.py
是我尝试运行的脚本:
import pika
from . import create_app
class PikaMassenger():
def __init__(self, *args, **kwargs):
pass
def consume(self, keys, callback):
pass
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.conn.close()
def start_consumer(app):
def callback(ch, method, properties, body):
try:
print("Event recieved %r" % body)
with app.app_context():
pass
except Exception as e:
print("Consuming event %s failed: %s" % (method.routing_key, str(e)))
with PikaMassenger() as consumer:
consumer.consume(keys=['user.*', ], callback=callback)
if __name__ == "__main__":
app = create_app()
start_consumer(app)
我的
__init__.py
只包含应用程序工厂(create_app
)。我的Dockerfile和docker-compose如下:
Dockerfile
:FROM python:3.6
COPY requirements.txt /app/requirements.txt
WORKDIR /app
RUN pip install -r requirements.txt
COPY . /app
ENV SECRET_KEY dev
ENV FLASK_APP run.py
CMD flask run
docker-compose.yaml
:
app:
build:
context: ./app
expose:
- "5000"
- PYTHONUNBUFFERED=1
restart: on-failure
app_consumer:
build:
context: ./app
command: python -m messenger.py
environment:
- PYTHONUNBUFFERED=1
restart: on-failure
depends_on:
- rabbitmq
我想做的是使用相同的 Dockerfile
运行两个容器,并在其中一个中覆盖 command
参数,我知道基于上述细节,会出现错误:
File "/app/massenger.py", line 2, in <module>
from . import create_app
ImportError: attempted relative import with no known parent package
也许我需要在
docker-compose.yaml
中更改工作目录,或以不同的方式运行我的脚本。如果需要更多细节或者您想让我尝试一些东西,请告诉我。