Django message元件

2023-07-24 18:01:06

使用message元件要在seetings中設定

①INSTALLED_APPS   (專案需要什麼功能都放在這 既可以有資料庫,又可以寫程式碼,html檔案,和自己寫的APP一個道理) 

②MIDDLEWARE 中介軟體 (請求進來做什麼,請求走的時候做什麼)

 ③TEMPLATES  (模板,在html頁面中操作方便)

 ④第四個位置可以放在任意地方 有三種設定(將資料儲存在cookie中或session中,或者全部儲存)

 

使用方法

設定值

第一個引數request .第二個引數 訊息的級別,messages.SUCCESS不一定要這麼寫.第三個引數,自己寫具體的引數.  以列表的形式存在

1 from django.contrib import messages
2 messages.add_message(reqeust, messages.SUCCESS, "刪除成功")
3 messages.add_message(reqeust, messages.ERROR, "刪除失敗")

在檢視中讀取值(使用python程式碼)  迴圈讀取到messages, 讀取到的同時並刪除 (類裡面寫的__iter__方法所以可以迴圈)

1 from django.contrib.messages.api import get_messages
2 messages = get_messages(request)
3 for msg in messages:
4     print(msg)

使用html程式碼讀取值

<ul>
    {% for message in messages %}
        <li>{{ message.tags }} {{ message }}</li>
    {% endfor %}
</ul>

 

原始碼分析

message是一個物件(包裹),可以包裹很多資料

 1 class Message:
 2     """
 3     Represent an actual message that can be stored in any of the supported
 4     storage classes (typically session- or cookie-based) and rendered in a view
 5     or template.
 6     """
 7 
 8     def __init__(self, level, message, extra_tags=None):
 9         self.level = int(level)
10         self.message = message
11         self.extra_tags = extra_tags
12 
13     def _prepare(self):
14         """
15         Prepare the message for serialization by forcing the ``message``
16         and ``extra_tags`` to str in case they are lazy translations.
17         """
18         self.message = str(self.message)
19         self.extra_tags = str(self.extra_tags) if self.extra_tags is not None else None
20 
21     def __eq__(self, other):
22         if not isinstance(other, Message):
23             return NotImplemented
24         return self.level == other.level and self.message == other.message
25 
26     def __str__(self):
27         return str(self.message)
28 
29     @property
30     def tags(self):
31         return ' '.join(tag for tag in [self.extra_tags, self.level_tag] if tag)
32 
33     @property
34     def level_tag(self):
35         return LEVEL_TAGS.get(self.level, '')
View Code

 

request,level,message分別對應設定值時候的引數,extra_tags='':可以自己寫點東西,一般不用寫.fail_silently=False,是在if not fail_silently 做的一個例外處理,也就是說如果有異常了安安靜靜的在那不要報錯.

重點: messages = request._messages 在request中讀取到了一個物件,return messages.add(level, message, extra_tags) 呼叫了messages.add,把這個三個引數傳過去了.

 request_messages是在'django.contrib.messages.middleware.MessageMiddleware' 這個中介軟體中定義的,看是在第四個位置中哪個儲存的物件,SessionStorage物件(第四個位置設定的哪個就是那個物件)

所以messages = request._messages就是宣告了一個SessionStorage的物件(第四個位置設定的哪個就是那個物件),SessionStorage原始碼中範例化了這個物件,下面有呼叫了messages.add(level, message, extra_tags)方法,SessionStorage這個類中沒有message.add方法,在父類別BaseStorage中,接收了三個引數def add(self, level, message, extra_tags='').最後封裝給了message = Message(level, message, extra_tags=extra_tags), 總而言之繞了一圈,最終傳入進來的值都會封裝給Message物件

def add_message(request, level, message, extra_tags='', fail_silently=False):
    """
    Attempt to add a message to the request using the 'messages' app.
    """
    try:
    #SessionStorage的物件(第四個位置設定的哪個就是那個物件)
        messages = request._messages
"""
except AttributeError: if not hasattr(request, 'META'): raise TypeError( "add_message() argument must be an HttpRequest object, not " "'%s'." % request.__class__.__name__ ) if not fail_silently: raise MessageFailure( 'You cannot add messages without installing ' 'django.contrib.messages.middleware.MessageMiddleware' )
"""
else: return messages.add(level, message, extra_tags)

 

SessionStorage原始碼中範例化了這個物件

 

 

SessionStorage父類別中 

 

Message中

 1 class Message:
 2     """
 3     Represent an actual message that can be stored in any of the supported
 4     storage classes (typically session- or cookie-based) and rendered in a view
 5     or template.
 6     """
 7 
 8     def __init__(self, level, message, extra_tags=None):
 9         self.level = int(level)
10         self.message = message
11         self.extra_tags = extra_tags
12 
13     def _prepare(self):
14         """
15         Prepare the message for serialization by forcing the ``message``
16         and ``extra_tags`` to str in case they are lazy translations.
17         """
18         self.message = str(self.message)
19         self.extra_tags = str(self.extra_tags) if self.extra_tags is not None else None
20 
21     def __eq__(self, other):
22         if not isinstance(other, Message):
23             return NotImplemented
24         return self.level == other.level and self.message == other.message
25 
26     def __str__(self):
27         return str(self.message)
28 
29     @property
30     def tags(self):
      # 自己的tag和通過extra傳進來的tag都傳進來通過空格拼接
31 return ' '.join(tag for tag in [self.extra_tags, self.level_tag] if tag) 32 33 @property 34 def level_tag(self): 35 return LEVEL_TAGS.get(self.level, '')


level_tag拿到的就是下面這個字典,在seetings中還可以自定義

 

DEFAULT_TAGS