【问题标题】:How do I Send Request to EndPoint on application Startup如何在应用程序启动时向端点发送请求
【发布时间】:2020-05-12 08:44:14
【问题描述】:

我正在开发一个 Django 项目,该项目有一个 API 端点,该端点接收发布请求并向注册用户发送欢迎电子邮件,目前,我必须使用表单将此请求发送到端点,有没有办法从我的环境变量中手动读取电子邮件和名称并在我第一次运行应用程序后发送请求?像

EMAIL = 'try@test.com'
NAME = 'Bob'

我已经将它存储为环境变量

这是我当前的代码

@require_http_methods(["POST"])
@login_required
def add_user(request):
    if request.is_ajax():
        name = request.POST.get('name')
        email = request.POST.get('email')
        if not BlueUsers.objects.filter(user_email=email).exists():
            newuser_obj = BlueUsers.objects.create(user_name=name, user_email=email)
            conf_obj = Config.objects.first()
            if conf_obj:
                post_url = "{}/priv/create-user/".format(conf_obj.hostname)
                data = {
                    'name': newuser_obj.user_name,
                    'email': newuser_obj.user_email,
                    'redtree_user_id': newuser_obj.id
                }
                headers = {'data-auth-key': conf_obj.authentication_token}
                try:
                    response = requests.post(post_url, data=data, headers=headers)
                except:
                    response = None

我一直在努力解决这个问题

【问题讨论】:

  • 这是什么原因?鉴于这封电子邮件将在每次部署或其他应用程序重新启动时发送,作为用户收到这些通知会让我很烦。
  • 原因是我不想每次都手动填写表单,并且它只会执行一次,因为代码会在发送邮件之前检查用户是否已经存在

标签: python django django-models django-rest-framework django-forms


【解决方案1】:

有一个文件名apps.py 会加载您的应用配置并在应用启动时运行代码。

您的目的应该通过以下代码来实现

class MyAppConfig(AppConfig):
    name = "myapp"

    def ready(self):
        # your model and other imports here

        email = os.environ.get('EMAIL')
        name = os.environ.get('NAME')

        if not BlueUsers.objects.filter(user_email=email).exists():
            newuser_obj = BlueUsers.objects.create(user_name=name, user_email=email)
            conf_obj = Config.objects.first()
            if conf_obj:
                post_url = "{}/priv/create-user/".format(conf_obj.hostname)
                data = {
                    'name': newuser_obj.user_name,
                    'email': newuser_obj.user_email,
                    'redtree_user_id': newuser_obj.id
                }
                headers = {'data-auth-key': conf_obj.authentication_token}
                try:
                    response = requests.post(post_url, data=data, headers=headers)
                except:
                    response = None

您在 AppConfig 类的 ready 方法中编写的任何逻辑都将在每次启动时执行一次。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2018-02-07
    • 1970-01-01
    • 1970-01-01
    • 2017-06-19
    相关资源
    最近更新 更多