In django.contrib.auth.models.py, there is a function with a line under it at the top starting on 20
在django.contrib.auth.models.py中,有一个函数,其下面有一行,从20开始
def update_last_login(sender, user, **kwargs):
"""
A signal receiver which updates the last_login date for
the user logging in.
"""
user.last_login = timezone.now()
user.save()
user_logged_in.connect(update_last_login)
This last line looks weird to me, because it is calling a function, immediately after the definition. I've never considered calling a models.py file like it's a script, and I thought the django models are nothing more than definitions...when does this user_logged_in line get called? On any import of the models file, or what? If it only gets called when users log in, how does django know to only call it then? Thanks
这最后一行对我来说很奇怪,因为它在定义之后立即调用了一个函数。我从来没有考虑过调用一个models.py文件,就像它是一个脚本一样,我认为django模型只不过是定义......这个user_logged_in行什么时候被调用?在任何模型文件的导入,或什么?如果它只在用户登录时被调用,那么django如何知道只调用它呢?谢谢
1 个解决方案
#1
No, that is not calling the update_last_login
function; it is connecting it to a signal.
不,那不是调用update_last_login函数;它将它连接到信号。
All Python files are executable; even function and class definitions are executable code. Everything at module level - again, including function definitions - is executed when the file is first imported.
所有Python文件都是可执行的;偶数函数和类定义是可执行代码。模块级别的所有内容 - 包括函数定义 - 都会在首次导入文件时执行。
#1
No, that is not calling the update_last_login
function; it is connecting it to a signal.
不,那不是调用update_last_login函数;它将它连接到信号。
All Python files are executable; even function and class definitions are executable code. Everything at module level - again, including function definitions - is executed when the file is first imported.
所有Python文件都是可执行的;偶数函数和类定义是可执行代码。模块级别的所有内容 - 包括函数定义 - 都会在首次导入文件时执行。