python - 在 Django View 中诊断 AttributeError

标签 python django

在我的一个 Django 项目中,我编写了简单的 webhook 逻辑,如果满足某些条件,它会 ping 某个有效负载的 url。这是代码:

@csrf_exempt
def webhook_event(request,*args,**kwargs):
    if request.method == 'POST':
        data = json.loads(request.body)
        event_type = data['event']
        # use CDN URL from webhook payload
        if event_type == 'project.datafile_updated':
            url = data['data']['cdn_url']
            config_manager.set_obj(url)
            return json.dumps({'success':True}), 200, {'ContentType':'application/json'} 
        return json.dumps({'success':False}), 400, {'ContentType':'application/json'}
    else:
        return render(request,"404.html",{})

我正在使用以下内容对其进行测试:

import requests
import json

# Update project_id
project_id = "<some_id>"

data = {"timestamp": 1463602412, "project_id": project_id, "data": {"cdn_url": "https://cdn.example.com/json/{0}.json".format(project_id), "origin_url": "https://example.s3.amazonaws.com/json/{0}.json".format(project_id), "revision": 15}, "event": "project.datafile_updated"}

r = requests.post("http://127.0.0.1:8000/ohook/", data=json.dumps(data), headers={'Content-Type': 'application/json'})
print r

一切正常,但是 webhook_event 返回的元组给我以下错误:

Internal Server Error: /ohook/
Traceback (most recent call last):
  File "/home/hassan/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in get_response
    response = middleware_method(request, response)
  File "/home/hassan/.virtualenvs/myenv/local/lib/python2.7/site-packages/newrelic-2.56.0.42/newrelic/hooks/framework_django.py", line 328, in wrapper
    return wrapped(*args, **kwargs)
  File "/home/hassan/.virtualenvs/myenv/local/lib/python2.7/site-packages/django/middleware/clickjacking.py", line 30, in process_response
    if response.get('X-Frame-Options', None) is not None:
AttributeError: 'tuple' object has no attribute 'get'

谁能帮我诊断一下?

最佳答案

如错误所述,您将返回一个元组:JSON、一个整数(大概是状态代码)和一个字典(大概是标题)。

即使你修复了这个问题,你也不能只从 View 中返回 JSON;您必须返回 HttpResponse 或其子类之一的实例。

您应该使用 JsonResponse 而不是在您的 POST block 中执行 return json.dumps(...) .这接受 Python 数据结构并返回包含序列化 JSON 的响应;作为奖励,它还适本地设置了内容类型。

if event_type == 'project.datafile_updated':
    ...
    return JsonResponse({'success':True})
return JsonResponse({'success':False}, status=400)

(请注意,render 是一个明确的快捷方式,它呈现模板并将其作为 HttpResponse 返回;json.dumps() 不是这种情况。)

关于python - 在 Django View 中诊断 AttributeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44101374/

相关文章:

python - Google Cloud SQL w/Django - 连接速度极慢

python [:] notation and range

python - 测试 python 类对象实例

python - Django REST框架: nested serializer not properly validating data

python - django makemigrations 中的操作错误 1050 错误 “Table already exists”

python - 聚焦时不要设置 Gtk.TreeView 的选择?

Python 排序 - 半忽略大小写(a、aa、A、AA、b、bb、B、BB...)

python - 如何用字典中的数字替换 pandas 列中句子中的所有单词,然后对它们求和?

python - Django 通过 iOS 上传图片时图像旋转不正确(EXIF 问题)

python - ElasticSearch/Solr-产品站点的同义词?