Getting error django with rabbitmq ImproperlyConfigured: Requested setting REST_FRAMEWORK

14 Views Asked by At

Hi Guys I'm newbie in django i try to integrate microservices django with rabbitmq but i got the error like this

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

can someone help me

this is for my file manage.py

#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
from MicroserviceImage.listenerRabbitMq import Command
import threading


def main():
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MicroserviceImage.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)


def start_consuming(service_name):
    Command().handle()



if __name__ == '__main__':
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MicroserviceImage.settings')

    # Start the consumer threads

    consumer_threads = []
    for i in range(1):
        thread = threading.Thread(target=start_consuming, args=('crawler{}-service'.format(i),))

        consumer_threads.append(thread)


    # Start all the threads

    for thread in consumer_threads:

        thread.start()


    # Run the Django management command

    main()

and this is for setting.py

"""
Django settings for MicroserviceImage project.

Generated by 'django-admin startproject' using Django 4.1.13.

For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""

from pathlib import Path
# from dotenv import load_dotenv
import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-=6q8gd&filx^bh4)@!9c94ac9i_$b$#+g#m9h=_*ck$v9wc_sq'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'corsheaders',
    'django_dump_die',
    'CImgApp.apps.CimgappConfig',
    'CSentenceApp.apps.CsentenceappConfig'
]

CORS_ORIGIN_ALLOW_ALL = True

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django_dump_die.middleware.DumpAndDieMiddleware'
]

ROOT_URLCONF = 'MicroserviceImage.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'MicroserviceImage.wsgi.application'

# Websocket
CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("localhost", 6379)],
        },
    },
}

# Crontab
CELERY_BROKER_URL = 'redis://localhost:6379'

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 100,
    'DEFAULT_PARSER_CLASSES': [
        'rest_framework.parsers.JSONParser',
    ],
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.BrowsableAPIRenderer',
    ]
}

# RabbitMQ settings
RABBITMQ_SETTINGS = {
    'HOST': 'localhost',
    'PORT': 5672,
    'USERNAME': 'guest',
    'PASSWORD': 'guest',
    'VIRTUAL_HOST': '/',
    'EXCHANGE_NAME': 'django_api_exchange',
    'EXCHANGE_TYPE': 'direct',
    'QUEUE_NAME': 'django_api_queue',
    'ROUTING_KEY': 'django_api_routing_key',
}

# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': BASE_DIR / 'db.sqlite3',
#     }
# }
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django',
        'HOST': '127.0.0.1',
        'PORT': '3306',
        'USER': 'root',
        'PASSWORD': 'password'

    }
}

# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Jakarta'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

and this is for file listenerRabbitmq.py

import pika, json, os
from django.core.management.base import BaseCommand

from CImgApp import views as CImgAppViews

class Command(BaseCommand):
    help = 'Launches the queue listener'


    def handle(self, *args, **options):
        print(os.environ['DJANGO_SETTINGS_MODULE'])
        self.run()


    def run(self):

        connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))

        channel = connection.channel()


        channel.queue_declare(queue='crawler_queue')
        def callback(ch, method, properties, body):
            message = json.loads(body)
            task = message.get('task')
            request = json.loads(message.get('request'))
            print("[x] Received ", task)
            # print("[x] Received Request", request)
            
            if task == 'crawlerImage':
                if len(request) > 0:
                    for value in request:
                        print('asdas')
                        # CImgAppViews.botMainImg(value['daftarIsi'])
        #Jika Ingin Mengirim Queue Baru Dari Callback Gunakan Seperti Di Bawah
        channel.basic_consume(queue='crawler_queue', on_message_callback=callback, auto_ack=True)
        print(' [*] Waiting for messages. To exit press CTRL+C')
        channel.start_consuming()
        

so the error after i try to add code

from CImgApp import views as CImgAppViews

can someone help me i use python3 thank you

0

There are 0 best solutions below