为啥此 Django API 调用出现意外的关键字参数错误?
Posted
技术标签:
【中文标题】为啥此 Django API 调用出现意外的关键字参数错误?【英文标题】:Why is there an unexpected keyword argument error for this Django API call?为什么此 Django API 调用出现意外的关键字参数错误? 【发布时间】:2016-10-29 23:43:26 【问题描述】:我正在关注 Django-Restful 教程here,并编写了以下代码
在views.py中:
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET','POST'])
def snippet_list(request, format=None):
"""
List all snippets, or create a new snippet.
"""
if request.method == 'GET':
snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = SnippetSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data,status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
在 urls.py 中:
from django.conf.urls import url
from snippets import views
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [
url(r'^snippets/$',views.snippet_list),
url(r'^snippets/(?P<pk>[0-9]+)/$',views.snippet_detail)
]
urlpatterns = format_suffix_patterns(urlpatterns)
当我运行服务器时,我可以得到正常的http://127.0.0.1:8000/snippets/ 来返回标准的 JSON 响应,但是当我尝试访问时
http http://127.0.0.1:8000/snippets.json # JSON suffix
http http://127.0.0.1:8000/snippets.api # Browsable API suffix
我收到一个产生此回溯的错误:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/snippets.json
Django Version: 1.9.7
Python Version: 2.7.6
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'snippets',
'quickstart']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "/home/myname/workspace/restTutorial/env/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/home/myname/workspace/restTutorial/env/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/myname/workspace/restTutorial/env/local/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
Exception Type: TypeError at /snippets.json
Exception Value: snippet_list() got an unexpected keyword argument 'format'
为什么会出现这个错误?
编辑:链接到settings.py
【问题讨论】:
你能发布你的设置吗 这是 pastebin 上的文件副本:pastebin.com/kvTvaY6V。 @user1362215 您需要在发布设置时隐藏您的密钥。然后使用该链接更新问题。 完成。不过,这只是我正在学习的一个教程,所以安全性不是一个大问题。 请发布完整的堆栈跟踪,而不仅仅是最后一行。 【参考方案1】:问题是我在views.py
文件中有重复的函数,其中靠近底部的不同装饰器。删除它们解决了这个问题。
【讨论】:
【参考方案2】:试试这个
http http://127.0.0.1:8000/snippets.json # JSON suffix http
http://127.0.0.1:8000/snippets.api # Browsable API suffix
改为
http http://127.0.0.1:8000/snippets/?format=json
http http://127.0.0.1:8000/snippets/?format=api
【讨论】:
【参考方案3】:我遇到了一个类似的问题,我的错误是我在声明 urls 时使用了 Django 的反向模块,而不是 Django Rest Framework 的反向模块:
不要使用这个:
from django.urls import reverse
改用这个:
from rest_framework.reverse import reverse
@api_view(['GET'])
def api_root(request, format=None):
return Response(
#'users': reverse('users:user-list', request=request, format=format),
'transactions': reverse('transactions:transaction-list', request=request, format=format),
)
【讨论】:
以上是关于为啥此 Django API 调用出现意外的关键字参数错误?的主要内容,如果未能解决你的问题,请参考以下文章
get() 得到了一个意外的关键字参数“pk”:django
为啥我使用来自 Angular 服务的自签名证书调用 HTTPS API 时会出现此 ERR_CERT_AUTHORITY_INVALID 错误?
__init__() 在 python/django 中得到了一个意外的关键字参数“mime”
为啥我在 Django 中使用此调用从 Paypal 收到“内部错误”?