Django Test Client client.post()发送GET请求?

时间:2017-06-23 17:12:13

标签: django http

我是Python和Django的新手。我做了一个关于执行请求方法的实验(例如,对于某些网址,您只能使用GET)。这是我的代码。

tests.py

from django.test import TestCase, Client
client = Client()

class MyTests(TestCase):
    def test_request_method:
        """ Sending wrong request methods should result in 405 error """
        self.assertEqual(client.post('/mytest', follow = True).status_code, 405)

urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.index, name = 'index'),
    url(r'^mytest/', views.mytest, name = 'mytest'),
]

views.py

from django.http import HttpResponse

def mytest(request):
    if request.method == 'GET':
        return HttpResponse("Not implemented", status = 500)
    else:
        return HttpResponse("Only GET method allowed", status = 405)

但测试总是返回状态500。

我看到here这可能与在follow=True电话中使用client.post()有关。但是,如果我使用follow=False,我将获得状态301。

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:5)

是否可能将/mytest重定向到/mytest/The documentation建议默认情况下,如果没有带斜杠的URL模式匹配,则通过重定向添加尾部斜杠,并引用:

  

请注意,重定向可能会导致POST请求中提交的任何数据丢失。

由常用的重定向状态代码引起的请求始终是GET请求。您可以向/mytest/发出请求,也可以从网址格式中删除尾随斜杠。

相关问题