Django RabbitMQ消费者

7

我正在构建一个Django应用程序,多个外部应用程序将与其联系。 Django应用程序旨在提供UI并使用从外部应用程序接收的数据填充数据库。

最初的想法是使用 django_rest_framework,但这似乎会创建一个紧密耦合的系统,因为每个外部应用程序都必须通过REST调用联系Django应用程序。

我的另一个想法最好用一张图片来描述: http://imgur.com/vakZvQs 几个发布者将在RabbitMQ上创建消息,我的Django将消费它们并在数据库中创建适当的模型。

这样的做法可行吗?我已经使用了来自 pika 库的异步示例进行了发布者和消费者,并且消息如预期地流动。但是将Django加入其中会产生错误,例如:

RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label  

django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

代码摘录:

# pika consumer
def on_message(self, unused_channel, basic_deliver, properties, body):
        # invoking view function
        from myapp.views import create_one_foo
        create_one_foo()
        self.acknowledge_message(basic_deliver.delivery_tag)

# views.py
from .models import Foo

def create_one_foo():
    foo = Foo()
    foo.bar = "bar"
    foo.save()

你的问题似乎与RabbitMQ无关。我不了解Django,但你应该提供更多关于你的Django应用程序的细节,这样有经验的人才能回答。 - Jean-Sébastien Pédron
3个回答

1

我曾经遇到过类似的问题,通过在导入模型之前调用以下两行代码解决了该问题。

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "admin.settings")
django.setup()

然后

from .models import Foo

我仍在学习Django,如果我找到详细的解释,我会编辑我的答案。


0

使用本文创建消费者

import json
import pika
import django
from sys import path
from os import environ



path.append('/home/john/Dev/SECTION/Likes/Likes/settings.py') #Your path to settings.py file
environ.setdefault('DJANGO_SETTINGS_MODULE', 'Likes.settings') 
django.setup()
from likes.models import Quote

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost', heartbeat=600, blocked_connection_timeout=300))
channel = connection.channel()
channel.queue_declare(queue='likes')

def callback(ch, method, properties, body):
    print("Received in likes...")
    print(body)
    data = json.loads(body)
    print(data)

    if properties.content_type == 'quote_created':
        quote = Quote.objects.create(id=data['id'], title=data['title'])
        quote.save()
        print("quote created")
    elif properties.content_type == 'quote_updated':
        quote = Quote.objects.get(id=data['id'])
        quote.title = data['title']
        quote.save()
        print("quote updated")
    elif properties.content_type == 'quote_deleted':
        quote = Quote.objects.get(id=data)
        quote.delete()
        print("quote deleted")
channel.basic_consume(queue='likes', on_message_callback=callback, auto_ack=True)
print("Started Consuming...")
channel.start_consuming()


-1
看看celery:http://www.celeryproject.org它是一个框架,可以帮助创建基于RabbitMQ的worker。
在托管Django应用程序的主机上运行celery worker服务。如果您需要更改Django数据库的状态,只需导入Django模型并通过worker将数据放入数据库即可。否则,您可以在Django应用程序内部运行celery worker。

3
如果没有误解,TS希望Django从RabbitMQ中消费数据,而Celery的行为不同。Celery worker将成为消费者,我们的Django应用程序将成为生产者。 - Adiyat Mubarak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接