AssertionError: 302 != 200 : 無法檢索重定向頁面“/api/v2/app/nextdialog”:回應代碼為 302(預期為 200)
在 Django 中,可以有三個視圖,每個視圖都重定向到下一個視圖。視圖 1 重定向到視圖 2,視圖 2 重定向到視圖 3?
視圖.py:
class ConversationLayerView(generics.GenericAPIView):
permission_classes = (permissions.IsAuthenticated,)
def post(self, request, *args, **kwargs):
body = request.data
cardType = body["cardType"]
if cardType == "CHOICE":
serializer = appChoiceTypeSerializer(body)
elif cardType == "TEXT":
serializer = appTextTypeSerializer(body)
elif cardType == "INPUT":
serializer = appInputTypeSerializer(body)
else:
serializer = StartAssessmentSerializer(body)
validated_body = serializer.validate_value(body)
url = get_endpoint(validated_body)
reverse_url = encodeurl(body, url)
return HttpResponseRedirect(reverse_url)
class NextDialog(generics.GenericAPIView):
permission_classes = (permissions.AllowAny,)
def get(self, request, *args, **kwargs):
result = request.GET
data = result.dict()
contact_uuid = data["contact_uuid"]
step = data["step"]
value = data["value"]
description = data["description"]
title = data["title"]
if data["cardType"] == "CHOICE":
optionId = int(value) - 1
else:
optionId = data["optionId"]
path = get_path(data)
assessment_id = path.split("/")[-3]
request = build_rp_request(data)
app_response = post_to_app(request, path)
if data["cardType"] != "TEXT":
if data["cardType"] == "INPUT":
optionId = None
store_url_entry = appAssessments(
contact_id=contact_uuid,
assessment_id=assessment_id,
title=title,
description=description,
step=step,
user_input=value,
optionId=optionId,
)
store_url_entry.save()
pdf = pdf_ready(app_response)
if pdf:
response = pdf_endpoint(app_response)
return HttpResponseRedirect(response)
else:
message = format_message(app_response)
return Response(message, status=status.HTTP_200_OK)
class Reports(generics.GenericAPIView):
permission_classes = (permissions.AllowAny,)
def get(self, request, *args, **kwargs):
report_id = request.GET.get("report_id")
response = get_report(report_id)
return Response(response, status=status.HTTP_200_OK)
實用程式.py
def get_endpoint(payload):
value = payload["value"]
if value != "":
if value == "back":
url = reverse("app-previous-dialog")
elif value == "abort":
url = reverse("app-abort")
else:
url = reverse("app-next-dialog")
elif value == "":
url = reverse("app-start-assessment")
return url
def encodeurl(payload, url):
qs = "?" urlencode(payload, safe="")
reverse_url = url qs
return reverse_url
代碼說明:應用在 ConversationLayerView 中接收到一個 json 負載。它呼叫端點方法以根據有效負載中設定的“值”鍵來了解要重定向到哪個端點。
請求看起來像這樣:
{
"contact_uuid": "67460e74-02e3-11e8-b443-00163e990bdb",
"choices": null,
"value": "Charles",
"cardType": "INPUT",
"step": null,
"optionId": null,
"path": "",
"title": "",
"description": "What's your name",
"message": ""
}
由于“value”是“Charles”,因此視圖重定向到 NextDialog 視圖中的“app-next-dialog”。在此視圖中,向外部應用程式發出 POST 請求并收到 json 回應。如果回應具有 PDF 密鑰,則此視圖將重定向到第三個視圖。這發生在這里:
if pdf:
response = pdf_endpoint(app_response)
return HttpResponseRedirect(response)
else:
message = format_message(app_response)
return Response(message, status=status.HTTP_200_OK)
如果密鑰存在,則重定向到“回應”,其輸出為“/api/v2/app/reports?report_id=/reports/17340f51604cb35bd2c6b7b9b16f3aec”,否則不重定向但回傳 200。
錯誤:
AssertionError: 302 != 200 : Couldn't retrieve redirection page '/api/v2/app/nextdialog': response code was 302 (expected 200)
網址.py
path(
"api/v2/app/assessments",
views.PresentationLayerView.as_view(),
name="app-assessments",
),
path("api/v2/app/nextdialog", views.NextDialog.as_view(), name="app-next-dialog"),
path("api/v2/app/reports", views.Reports.as_view(), name="app-reports"),
test_views.py:
class appAssessmentReport(APITestCase):
data = {
"contact_uuid": "67460e74-02e3-11e8-b443-00163e990bdd",
"choices": None,
"message": (
"How old are you?\n\nReply *back* to go to "
"the previous question or *abort* to "
"end the assessment"
),
"explanations": "",
"step": 39,
"value": "27",
"optionId": None,
"path": "/assessments/f9d4be32-78fa-48e0-b9a3-e12e305e73ce/dialog/next",
"cardType": "INPUT",
"title": "Patient Information",
"description": "How old are you?",
}
start_url = reverse("app-assessments")
next_dialog_url = reverse("app-next-dialog")
pdf_url = reverse("app-reports")
destination_url = (
"/api/v2/app/nextdialog?contact_uuid="
"67460e74-02e3-11e8-b443-00163e990bdd&"
"choices=None&message=How old are you?"
"
Reply *back* to go to the "
"previous question or *abort* to end"
" the assessment&explanations=&step="
"39&value=27&optionId=None&path=/"
"assessments/f9d4be32-78fa-48e0-b9a3"
"-e12e305e73ce/dialog/next&cardType"
"=INPUT&title=Patient Information&"
"description=How old are you?"
)
@patch("app.views.pdf_ready")
@patch("app.views.post_to_app")
def test_assessment_report(self, mock_post_to_app, mock_pdf_ready):
mock_post_to_app.return_value = {
"cardType": "CHOICE",
"step": 40,
"title": {"en-US": "YOUR REPORT"},
"description": {"en-US": ""},
"options": [
{"optionId": 0, "text": {"en-US": "Option 1"}},
{"optionId": 1, "text": {"en-US": "Option 2"}},
{"optionId": 2, "text": {"en-US": "Option 3"}},
],
"_links": {
"self": {
"method": "GET",
"href": "/assessments/898d915e-229f-48f2-9b98-cfd760ba8965",
},
"report": {
"method": "GET",
"href": "/reports/17340f51604cb35bd2c6b7b9b16f3aec",
},
},
}
mock_pdf_ready.return_value = utils.pdf_ready(mock_post_to_app.return_value)
user = get_user_model().objects.create_user("test")
self.client.force_authenticate(user)
response = self.client.post(self.start_url, self.data, format="json")
print(response)
self.assertRedirects(response, self.destination_url)
到目前為止,這行不通。總之,我只是想從視圖 1 開始,重定向到視圖 2 并從視圖 2 重定向到視圖 3。這在 Django 中是否可行?謝謝。
uj5u.com熱心網友回復:
問題在于您的測驗,而不是視圖邏輯 - 完全有可能擁有一系列重定向。
assertRedirects檢查回應的狀態,默認情況下要求它是 HTTP 200 回應。因為您有一系列重定向,所以回應是 302(另一個重定向)而不是 200,這就是測驗失敗并出現錯誤“回應代碼為 302(預期為 200)”的原因。
您需要修改target_status_code引數以告知assertRedirects您期望回應具有 302 狀態代碼:
self.assertRedirects(response, self.destination_url, target_status_code=302)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/461487.html
