【问题标题】:Rendering Received Webhook Payload by Django Views由 Django 视图渲染接收到的 Webhook 有效负载
【发布时间】:2020-04-24 11:45:08
【问题描述】:

开发平台:

  • Python 3.6.2
  • Django 3.0
  • Windows 10 VScode

问题:

我无法在 django 模板通过相同的视图方法或重定向。此外,我无法使用 django 会话变量将有效负载数据传递到另一个视图。根据打印语句,似乎不存在会话。看起来我错过了一些重要的东西。

详情: 设置.py 我的会话中间件和安装的应用程序设置也针对基于 cookie 的会话进行了正确设置。

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    # 'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'

在使用 ngrok 公开我的本地开发服务器后,我在 mailchimp 上配置了我的 webhook url。 例如

34nghirt345.ngrok.io/webhook

在我的 url 配置中如下:

urls.py

path('webhook/', views.my_webhook_view),
path('webhook/<str:some_id>/', views.webhook_renderer, name ="url_webhook_renderer"),

我在配置的 url 路径从 mailchimp 接收 webhook 有效负载,并且能够在相应的视图方法中处理有效负载。

views.py

@csrf_exempt
def my_webhook_view(request):
    # Mailchimp webhook receiver for mailchimp batch operations.
    context = {}
    if request.method == 'POST':
        print('Webhook Payload Received')
        logger.debug(f"Some ID: {request.POST.get('data[id]')}")
        payload_dict = {k:v for k,v in request.POST.items()}
        logger.debug(f"Dict of POST DATA: {payload_dict}")
        context = {
            'some_id': payload_dict['data[id]']
        }
        print("Webhook Post session items Before: ",request.session.items())
        request.session["context"] = context
        request.session.modified = True
        # I have also used SESSION_SAVE_EVERY_REQUEST = True as well but that didn't work either.
        print("Webhook Post session items After: ",request.session.items())

        #return render(request, "webhooks/webhook_rendering.html", context = context)
        return redirect('url_webhook_renderer', batch_id = context['some_id'])

def webhook_renderer(request, batch_id):
    print("Webhook rendering session passed context:",request.session.get('context'))
    print("Webhook rendering session items:",request.session.items())
    context = request.session.get('context')
    return render(request, "webhooks/webhook_rendering.html", context = context)

控制台输出:

从 my_webhook_view 打印语句

Webhook Post session items Before: dict_items([]) Webhook Post

会话项目之后:dict_items([('context', {'batch_id':'some_id'})])

从 webhook_renderer 打印语句

Webhook 渲染会话传递的上下文:无

Webhook 渲染会话项:dict_items([])

webhook_rendering.html

{% extends "index.html" %}
{% block content %}
    <p> {{ some_id }} </p>
{% endblock content %}

【问题讨论】:

    标签: python django session django-views webhooks


    【解决方案1】:

    Django 视图是无状态的,这意味着您收到的每个request 对其他请求对象一无所知。 my_webhook_view 中的request 对象与webhook_renderer 中的request 对象是完全不同的对象,您在其中一个对象上设置的任何属性都无法在另一个对象中访问。

    如果您想访问从您的 webhook 接收到的数据,您需要将数据保存到您的数据库或缓存中,或两者兼而有之。

    【讨论】:

    • @莫妮卡。在对视图之间传递数据进行了一些研究之后,人们建议使用 django 会话中间件。您是否建议其不正确的程序。例如 stackoverflow.com/questions/7763115/…stackoverflow.com/questions/42111303/…
    • @FarhanS 在这种情况下,使用会话没有意义。 webhook 视图的session 与mailchimp 相关,而呈现视图的session 与最终用户相关。
    猜你喜欢
    • 2014-11-25
    • 2015-04-29
    • 1970-01-01
    • 2019-03-10
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    • 2013-05-01
    • 2020-03-07
    相关资源
    最近更新 更多