Rendering Received Webhook Payload by Django Views

喜夏-厌秋 提交于 2020-01-16 08:58:08

问题


Dev Platform:

  • Python 3.6.2
  • Django 3.0
  • Windows 10 VScode

Problem:

I'm not able to render the received webhook payload on the django template via same view method or by redirect. Also I'm not able to use django sessions variable to pass payload data to another view. Seems like no session exist as per the print statements. Looks like I'm missing something cirtical.

Details: settings.py My sessions middleware and installed app settings are properly set as well for cookie based sessions.

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'

I've configured my webhook url on mailchimp after exposing my local dev server using ngrok. For example

34nghirt345.ngrok.io/webhook

and also in my url config as follows:

urls.py

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

I'm receiving webhook payload from mailchimp at the configured url path and is able to process the payload within the respective view method.

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)

Console Output:

Prints statements form my_webhook_view

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

session items After: dict_items([('context', {'batch_id':'some_id'})])

Print statements from webhook_renderer

Webhook rendering session passed context: None

Webhook rendering session items: dict_items([])

webhook_rendering.html

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

回答1:


Django views are stateless, meaning that each request you receive, knows nothing of other request objects. The request object in my_webhook_view is a completely different object than the request object in webhook_renderer, and any attributes you set on one will not be accessible in the other.

If you want access to data received from your webhook, you will need to save the data to your database, or a cache, or both.



来源:https://stackoverflow.com/questions/59620451/rendering-received-webhook-payload-by-django-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!