Twiiter、Webhooks 和 Django CRC Check --> 'str'对象没有属性'xframe_options_exempt'



我正在将Django用于我的Web应用程序,并已调整了教程@https://developer.twitter.com/en/docs/accounts-and-users/subscribe-account-activity/guides/securing-webhooks在Python 3中运行,但是我在视图中遇到了这个问题

from django.shortcuts import render
from django.http import HttpResponse, HttpRequest
import base64, hashlib, hmac, json
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.clickjacking import xframe_options_exempt
from django.views.decorators.http import require_GET

@csrf_exempt
@xframe_options_exempt
def twitter_webhook(request):
msg = request.GET.get('crc_token')
msg_bytes = msg.encode()
sha256_hash_digest = 
hmac.new(b'bEfpTIneaasdf876asd9f87908709asdf76789689as7dfH', msg_bytes, digestmod=hashlib.sha256).digest()
resp = 'sha256=' + str(sha256_hash_digest)
twitter_response = {
'response_token': resp
}
return json.dumps(twitter_response)

"tr"对象没有属性"xframe_options_exclude">

使用pycharm,我已经一步一步地调试了我的代码,返回适当的哈希值直到它被点击劫持中间件捕获为止,一切都很好。

Request Method: GET
Request URL:    http://127.0.0.1:8000/twitter?crc_token=1230983450923485
Django Version: 2.1.4
Exception Type: AttributeError
Exception Value:    
'str' object has no attribute 'xframe_options_exempt'
Exception Location:  
C:UsersmichaAppDataLocalProgramsPythonPython37libsite- 
packagesdjangoviewsdecoratorsclickjacking.py in wrapped_view, line 51
Python Executable:   
C:UsersmichaAppDataLocalProgramsPythonPython37python.exe
Python Version: 3.7.1
Python Path:    
['C:\Users\micha\Documents\Projects\sinclaire_webhooks',
'C:\Program Files\JetBrains\PyCharm 2018.3.1\helpers\pydev',
'C:\Users\micha\Documents\Projects\sinclaire_webhooks',
'C:\Program Files\JetBrains\PyCharm '
'2018.3.1\helpers\third_party\thriftpy',
'C:\Program Files\JetBrains\PyCharm 2018.3.1\helpers\pydev',
'C:\Users\micha\.PyCharm2018.3\system\cythonExtensions',
'C:\Users\micha\AppData\Local\Programs\Python\Python37\python37.zip',
'C:\Users\micha\AppData\Local\Programs\Python\Python37\DLLs',
'C:\Users\micha\AppData\Local\Programs\Python\Python37\lib',
'C:\Users\micha\AppData\Local\Programs\Python\Python37',
'C:\Users\micha\AppData\Local\Programs\Python\Python37\lib\site- packages',
'C:\Program Files\JetBrains\PyCharm '
'2018.3.1\helpers\pycharm_matplotlib_backend']
Server time:   Sun, 16 Dec 2018 17:58:20 +0000

我已经搜索过了,找不到任何明确的东西来引导我解决这个问题,作为python和django的新手,任何帮助都将不胜感激!

问题是,您直接从视图返回一个JSON字符串,这会导致xframe_options_exempt装饰器崩溃,因为它需要一个HttpResponse。Django视图函数应该返回一个HttpResponse

您可以修改视图以返回HttpResponse,如下所示:

return HttpResponse(json.dumps(twitter_response), content_type='application/json')

或者使用JsonResponse(HttpResponse的子类(,让Django处理字典到JSON:的转换

from django.http.response import JsonResponse
...
@csrf_exempt
@xframe_options_exempt
def twitter_webhook(request):
...
twitter_response = {
'response_token': resp
}
return JsonResponse(twitter_response)  # No need to use json.dumps()

相关内容

  • 没有找到相关文章

最新更新