V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
takanasi
V2EX  ›  Python

django 的信号是什么原理?

  •  
  •   takanasi · 2017-10-14 16:46:01 +08:00 · 3364 次点击
    这是一个创建于 2376 天前的主题,其中的信息可能已经有所发展或是发生改变。
    from django.dispatch import Signal
    
    user_logged_in = Signal(providing_args=["request", "user"])
    
    # Typically followed by `user_logged_in` (unless, e-mail verification kicks in)
    user_signed_up = Signal(providing_args=["request", "user"])
    

    怎么样才能触发这两个信号?

    6 条回复    2017-10-14 20:43:32 +08:00
    takanasi
        1
    takanasi  
    OP
       2017-10-14 16:49:23 +08:00
    四个小时前是鬼
    TanLian
        2
    TanLian  
       2017-10-14 16:51:36 +08:00   ❤️ 1
    user_logged_in.send(sender=xx,request=xx,user=xx)
    user_signed_up.send(sender=xx,request=xx,user=xx)
    上面这两句就是触发这两个信号了,不过你还要先定义接收函数,如

    @receiver(user_logged_in)
    def 某函数
    takanasi
        3
    takanasi  
    OP
       2017-10-14 17:15:14 +08:00
    @TanLian 大概理解了
    sender 我写 self 没事吧?
    EchoUtopia
        4
    EchoUtopia  
       2017-10-14 17:20:29 +08:00   ❤️ 1
    原理的话很简单,signal 里面有个 receivers 属性,是个 list, 有函数被 receiver 装饰了,就把这个函数 append 到 signal 的 receivers 属性里。然后调用这个 signal.send 函数的时候,就依次调用 receivers 里面的函数
    workwonder
        5
    workwonder  
       2017-10-14 18:12:45 +08:00 via Android
    我用的 arango-orm 库由于没有事件机制,我就自己写了,你可以看下相当简单的,还有单元测试。
    https://github.com/wonderbeyond/arango-orm/commit/1559cba970ea28fe96536efb739f8d558ef7370d
    wcsjtu
        6
    wcsjtu  
       2017-10-14 20:43:32 +08:00
    其实就是定义了一个 signal: handler 的映射, 你发送信号时, 会去搜索对应的回调函数然后调用
    看看 django/dispatch/dispatcher.py 文件中的 Signal.send 函数, `receiver`就是信号接收函数,也就是 receiver 修饰器修饰的函数。 感觉这段代码,平平无奇啊~ 没有黑科技的感觉

    ```python
    def send(self, sender, **named):
    responses = []
    if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS:
    return responses

    for receiver in self._live_receivers(sender):
    response = receiver(signal=self, sender=sender, **named)
    responses.append((receiver, response))
    return responses

    ```
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3464 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 12:00 · PVG 20:00 · LAX 05:00 · JFK 08:00
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.