簡體   English   中英

Django RabbitMQ 消費者

[英]Django RabbitMQ consumer

我正在構建一個 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()

我有類似的問題,通過在導入模型之前調用這兩行來解決。

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

接着

from .models import Foo

我還在學習 django,如果我找到詳細的解釋,我會編輯我的答案

使用本文創建消費者

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()

看看 celery: http ://www.celeryproject.org 這是一個幫助創建基於 RabbitMQ 的工作人員的框架

在 Django 應用所在的主機上運行 celery worker 服務。 如果您需要更改 Django DB 的狀態,只需導入 Django 模型並由 worker 將數據放入數據庫。 否則,您可以在 Django 應用程序中運行 celery workers。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM