首先我们来说一说,post与get的区别 POST和GET差异:
HTTP没有要求,如果Method是POST数据就要放在BODY中。也没有要求,如果Method是GET,数据(参数)就一定要放在URL中而不能放在BODY中。
HTTP协议对GET和POST都没有对长度的限制 HTTP协议明确地指出了,HTTP头和Body都没有长度的要求。而对于URL长度上的限制,有两方面的原因造成:
首先在view中定义一个post请求, django 2.0.5 Python 3.6.5
views中的请求函数
def apis(request):
print("hello input")
# p={"word":"data"}
#查看客户端发来的请求,前端的数据
print("request.body={}".format(request.body))
#返回给客户端的数据
result="success"
if request.method=="POST":
print(request.POST)
return JsonResponse({"status": 200, "msg": "OK","data": result})
由于是post的请求,所以其请求体在request.body中,即客户端发过来的请求,即前端发过来的参数。一般都会对参数进行处理,之后返回result再次传输给前端,这里我没有进行处理,直接返回给以一个result.
之后配置url
最后新建一个client(客户端)来测试接口是否成功。这里是使用django 自带的tests.py 写了一个函数。
from django.test import TestCase
# Create your tests here.
import requests,json
def dodo():
req={34:1}
url='http://127.0.0.1:8000/apis'
#params 为发送给服务器的请求
params = {
"name":"前端输入参数"
}
#请求头,是浏览器正常的就行
headers = {"User-agent":"none/ofyourbusiness","Spam":"Eggs"}
#发送请求,返回新数据
data = requests.post(url,data=params,headers=headers)
print(data)
print(data.text)
dodo()
运行结果如上,表示成功。 我是做算法的,可能对于后端来说这个很简单,但是对于我这个算法来说弄了小半天。终于解决了,记录一下。
以下为参考的用django实现的获取用户输入方法示例。
URLS 配置 #urls.py from django.conf.urls.defaults import * from mysite.views import search , result # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^mysite/', include('mysite.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# (r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^$', search),
(r'^search/$', result)
)
VIEW.py配置
#views.py
#-*- coding: UTF-8 -*-
from django.shortcuts import render_to_response
def search(request):
return render_to_response('search.html')
def result(request):
key = request.GET['q']
if not key :
message = u'请输入搜索内容'
return render_to_response('result.html',{'message':message})
else :
message = u'你输入的是' + key
return render_to_response('result.html',{'message':message})
<html><!--search.html-->
<head>
<title>Search</title>
</head>
<body>
<form action="/search/" method="get">
<input type="text" name="q">
<input type="submit" value="Search">
</form>
</body>
</html>
<html><!--result.html-->
<head>
<title>Search</title>
</head>
<body>
{{message}}
</body>
</html>