django 4.2 自定义signal的使用方法

环境:win11 python3.9.2 django 4.2.11

背景:执行异步数据存储,想要使用该方法实现(失败了)

时间:20240410

说明:记录一下,避免忘记

1、创建django项目,并实现首页

python 复制代码
# 创建项目
django-admin startproject getfiction .  

# 在目录下新建views.py,并写入如下内容
# TestSignal/views.py

from django.shortcuts import HttpResponse


def index(request):
    return HttpResponse("OK")

# 修改路由
# TestSignal/urls.py

from django.contrib import admin
from django.urls import path
from TestSignal.views import index

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index)
]

测试:

2、创建信号并实现执行

python 复制代码
# TestSignal/views.py

from django.shortcuts import HttpResponse
from django.dispatch import Signal, receiver

# 创建信号
my_signal = Signal()


@receiver(my_signal)
def test_signal(sender, **kwargs):
    return kwargs['info']


def index(request):
    msg = my_signal.send(sender=None, info="hello world")
    return HttpResponse(str(msg[0][1]))

执行结果

相关推荐
小王同学666619 小时前
Django 5 中实现文件上传功能
数据库·django·sqlite
vx-程序开发20 小时前
【java项目分享】springboot农产品销售平台14952
java·javascript·spring boot·python·eclipse·django·php
qq_22589174662 天前
基于Python的外卖订单数据分析可视化系统
python·信息可视化·django
酩酊仙人2 天前
Windows Server部署django
windows·django·sqlite
倒流时光三十年2 天前
第三阶段 26 · highlight 高亮(返回命中片段)
后端·python·django
黑桃小柒73 天前
Django模型关系:从一对多到多对多全解析
数据库·django·sqlite
Python私教3 天前
Django + AI 做智能工单系统:自动分类、重复合并、服务时限与人工审批实战
人工智能·python·django