django POST 不能 return 字符串
django POST can't return character string
我尝试测试我的服务器并使用 django 连接 android 客户端。现在我的代码是
from django.http import HttpResponse
def first_page(request):
if request.method == 'POST':
return HttpResponse('you are post method')
android 客户端 post 我的服务器总是 500 响应。如果更改 method.and 使用 if request.method == 'GET:'
它有效...我很困惑发生了什么...'POST
方法不能使用 HttpResponse
?
更新我的问题:
我们使用 java 到 POST
我的 django server.and return 错误如打击
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getHeaderField(Unknown Source)
at java.net.URLConnection.getContentType(Unknown Source)
有什么可以帮助我们的吗?
我会让你的观点更稳健一点,以确保你不会忽略一个愚蠢的错误。你的视图应该总是 return 一个 HttpResponse
对象,所以在 if
块之后添加一个 return,像这样:
from django.http import HttpResponse, HttpResponseBadRequest
def first_page(request):
if request.method == 'POST':
return HttpResponse('you are post method')
return HttpResponseBadRequest('Request type {} is not allowed'.format(request.method))
或者添加 django 的内置请求类型装饰器以在您的视图代码运行之前要求 post:
from django.http import HttpResponse
from django.views.decorators.http import require_POST
@require_POST
def first_page(request):
return HttpResponse('you are post method')
然后确保您已将 settings.DEBUG 设置为 True 并查看您从 android 客户端获得的结果。
您是否在您的函数中加入了 CSRF 豁免功能区?
@csrf_exempt
def my_method(request):
哦!!!!我解决它。我使用 django 1.77 并且默认加载了很多中间件! #
中间件就ok了!
我尝试测试我的服务器并使用 django 连接 android 客户端。现在我的代码是
from django.http import HttpResponse
def first_page(request):
if request.method == 'POST':
return HttpResponse('you are post method')
android 客户端 post 我的服务器总是 500 响应。如果更改 method.and 使用 if request.method == 'GET:'
它有效...我很困惑发生了什么...'POST
方法不能使用 HttpResponse
?
更新我的问题:
我们使用 java 到 POST
我的 django server.and return 错误如打击
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getHeaderField(Unknown Source)
at java.net.URLConnection.getContentType(Unknown Source)
有什么可以帮助我们的吗?
我会让你的观点更稳健一点,以确保你不会忽略一个愚蠢的错误。你的视图应该总是 return 一个 HttpResponse
对象,所以在 if
块之后添加一个 return,像这样:
from django.http import HttpResponse, HttpResponseBadRequest
def first_page(request):
if request.method == 'POST':
return HttpResponse('you are post method')
return HttpResponseBadRequest('Request type {} is not allowed'.format(request.method))
或者添加 django 的内置请求类型装饰器以在您的视图代码运行之前要求 post:
from django.http import HttpResponse
from django.views.decorators.http import require_POST
@require_POST
def first_page(request):
return HttpResponse('you are post method')
然后确保您已将 settings.DEBUG 设置为 True 并查看您从 android 客户端获得的结果。
您是否在您的函数中加入了 CSRF 豁免功能区?
@csrf_exempt
def my_method(request):
哦!!!!我解决它。我使用 django 1.77 并且默认加载了很多中间件! #
中间件就ok了!