Wafiat
Wafiat

Reputation: 11

Django messages not saved when a new request is called inside a view

I am trying to make a message/logging system where the user/front-end can get the progress status of the process currently running in a thread they initiated (what they started, where the process is currently at, did it successfully finished, or if its error, pass the error message). There is already a logging mechanism which saves the info to a .log file, but since I want it to be sent to the user who requested it, I used django.messages instead.

I have set up my django settings as such:


INSTALLED_APPS = [
    ...
    'django.contrib.messages',
    ...
]
MIDDLEWARE = [
    ...
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    ...
]
TEMPLATES = [
    {
        ...
        'OPTIONS': {
            'context_processors': [
                ...
                'django.contrib.messages.context_processors.messages',
                ...
            ],
        },
    },
]
MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'

and I have this view:

from django.contrib import messages
from django.contrib.messages import get_messages
from django.shortcuts import render, redirect
from django.contrib.auth.models import User

from threading import Thread
from .logging_view_testing import try_catch
import logging

def index(request):
    if(True):
        thread = Thread(target=function_one, args=(request, ))
        thread.start()
    message_list = []

    storage = get_messages(request)
    for message in storage:
        message_list.append(message)
    storage.used = False

    tag_filter = request.GET.get('tag', None)
    if tag_filter:
        message_list = [message for message in message_list if tag_filter in message.tags.split()]

    context = {
        'username' : username,
        'messages': message_list,
    }

    return render(request, 'logging.html', context)

def function_one(request):
    try:
        try_catch(request)
        raise Exception("error executing function")
    except Exception as exc:
        print("0")
        messages.error(request, f"ERROR: {str(exc)}")
        print(f"{str(exc)}")
        logging.debug(exc)

which calls a function from another view:

from django.contrib import messages
import logging

def try_catch(request):
    try:
        try:
            message = "try_catch"
            messages.info(request, f"INFO: {message}")
            logging.debug(message)

            // not working after this line of code
            response = requests.get('https://', params={})
            messages.info(request, "INFO: got response")

            raise Exception("error executing function")
        except Exception as exc:
            messages.error(request, f"ERROR: {str(exc)}")
            print(f"{str(exc)}")
            logging.debug(exc)
            raise Exception("error executing function")
    except Exception as exc:
        messages.error(request, f"ERROR: {str(exc)}")
        print(f"{str(exc)}")
        logging.debug(exc)

this is the html/template:

<section> {% if messages %} <table class="messages">
    <tbody> {% for message in messages %} <tr{% if message.tags %} class="{{ message.tags }}" {% endif %}>
        <td>{{ message }}</td>
        </tr> {% endfor %} </tbody>
  </table> {% endif %} 
</section>

Note that there is this code:

// not working after this line of code
response = requests.get('https://', params={})
messages.info(request, "INFO: got response")

After testing the messaging service, I found out several things which I think shouldn't have happened:

  1. messages.debug does not get saved, I cant seem to save it. (info/success/error behaves normally).
  2. the messages are no longer saved into the user session storage after the code requests.get() is called, even though the passed request object isn't changed (it returns the same value of what is passed through the function).

Are there anything I'm doing wrong? any solutions? Thanks in advance.

Upvotes: 1

Views: 51

Answers (0)

Related Questions