所以我試圖創建一個PUT端點來編輯帖子資料。在這個端點中,帖子的id是在URL中給出的,然后新的帖子日期被插入到物體中。我遇到的問題是,請求沒有通過認證器(我使用Cognito來認證,對錯誤來說并不太重要)。因此,盡管你可以看到我清楚地傳入了資料,但在cognito_authenticator函式中的wrapped_view上,請求并沒有通過。為什么會發生這種情況?我得到的錯誤是:
"wrapped_view "是一個很好的例子。
"wrapped_view() 缺少 1 個必要的位置引數:'require'" Test.py View.py 認證器 uj5u.com熱心網友回復: 對于基于函式的視圖,你不需要使用
標籤: 上一篇:顯示svg檔案的系結串列def test_edit(self)。
response = self.client.put(reverse('edit_post_by_id', kwargs={'post_id': str(self.post.uuid)}) 。
data={'body': 'update text #update'},
content_type='application/json',
**{'HTTP_AUTHORIZATION': f'bearer {self.cognito.access_token}'})
self.assertEqual(response.status_code, status.HTTP_200_OK)
@api_view(['PUT'/span>])
@method_decorator(cognito_authenticator)。
def edit_post(request, post_id) 。
try:
post = Post.objects.get(pk=post_id)
except Post.DoesNotExist。
return JsonResponse(dict(error=f'Post id: {post_id}不存在'), status=status.HTTP_400_BAD_REQUEST)
def cognito_authenticator(view_func=None) 。
if view_func is None。
return partial(cognito_authenticator)
@wraps(view_func)
def wrapped_view(request, *args, **kwargs) 。
# 檢查請求中的cognito token。
auth = request.headers.get("Authorization", None)
if not auth:
return Response(dict(error='authorization header expected'), status=status.HTTP_401_UNAUTHORIZED)
parts = auth.split()
if parts[0].lower() != " bearer":
return Response(dict(error='Authorization header must start with bearer') 。
status=status.HTTP_401_UNAUTHORIZED)
elif len(partes) == 1:
return Response(dict(error='Token not found'), status=status.HTTP_401_UNAUTHORIZED)
elif len(parts) > 2:
return Response(dict(error='Authorization header must be Bearer token')。
status=status.HTTP_401_UNAUTHORIZED)
token = parts[1]
try:
res = decode_cognito_jwt(token)
except 例外。
# Fail if invalid[/span]。
return Response("Invalid JWT", status=status.HTTP_401_UNAUTHORIZED) # Or HttpResponseForbidden()
else:
# 繼續查看,如果有效的話。
return view_func(request, *args, **kwargs)
return wrapped_view
method_decorator所以:@api_view(['PUT'/span>])
@cognito_authenticator
def edit_post(request, post_id) 。
...
