Using flash text in django

Viewed 65

I am trying to use flash text in django. I think that KeyWordProcessor should be called only once. So i have defined it in settings.py file as this:

settings.py

KEYWORD_PROCESSOR = None

Then i am calling function KeywordProcessor() on app start like this:

apps.py

from django.apps import AppConfig

class MywebappConfig(AppConfig):
    name = 'mywebapp'

    def ready(self):
        import mywebapp.signals
        from flashtext import KeywordProcessor
        from django.conf import settings
        from mywebapp.utils import add_all_kewords_to_flash_text
        import threading

        settings.KEYWORD_PROCESSOR = KeywordProcessor()
        add_all_kewords_to_flash_text()

        t1 = threading.Thread(target=add_all_kewords_to_flash_text)
        t1.start()

utils.py

def add_keyword_to_flash_text(keyword_obj):

    if not settings.KEYWORD_PROCESSOR:
        raise ValueError("Flash text is None")

    added = settings.KEYWORD_PROCESSOR.add_keywords_from_dict(
        {keyword_obj.keyword: [keyword_obj.keyword]+keyword_obj.tags}
        )    


def add_all_kewords_to_flash_text():
    add_all_kewords = [add_keyword_to_flash_text(k) for k in KeyWord.objects.all()]

But i am getting this error: ValueError: Flash text is None

1 Answers

The settings file is there to define constants and you shouldn't be attempting to mutate constants (I.E it's immutable).

You can't change the settings after they have been loaded. So trying to do

settings.KEYWORD_PROCESSOR = KeywordProcessor()

Isn't going to work.

Take a closer look at the documentation

You're probably better writing a class to handle this, and initiating the class in the app config ready method.

class MyKeywordProcessor:
    def __init__(self):
        self.keyword_processor = KeywordProcessor()

Then in app config

class MywebappConfig(AppConfig):
    name = 'mywebapp'

    def ready(self):
        ...

        keyword_processor = MyKeywordProcessor()
        add_all_kewords_to_flash_text(keyword_processor)
        ...

As you can see I've passed the keyword processor to your add_all_kewords_to_flash_text function which is the instance of the KeywordProcessor object.

Related