如何用Django实现一个回吐请求参数的接口
在views.py文件
from django.shortcuts import render_to_response #返回页面用
from django.http import HttpResponse
import json
import re
#GET接口,返回全部URL参数二
def get_Info(request):
result = {}
if request.method == 'GET':
for k, v in request.GET.items():
result[k]= v
result = json.dumps(result)
return HttpResponse(result)
else:
return render_to_response('login.html')
#POST接口,根据header返回表单或body参数
def post_Info(request):
if request.method == 'POST' and request.META.get('CONTENT_TYPE') == "application/x-www-form-urlencoded":
params = ""
username = request.POST.get('username')
password = request.POST.get('password')
card_id = request.POST.get('card_id')
params = "用户名:"+username + "密码:" + password + "身份证:" + card_id
# params = json.dumps(params)
return HttpResponse(params)
elif request.method == 'POST' and request.META.get('CONTENT_TYPE') == "application/json":
params = ""
params = json.loads(request.body)
params = json.dumps(params)
return HttpResponse(params)
elif request.method == 'POST' and request.META.get('CONTENT_TYPE') == "application/json" and request.COOKIES['test_Cookie']!=None:
return excu_Cookie(request.COOKIES['test_Cookie'])
else:
return render_to_response('post_data.html')
#优化一下表单post接口
def post_Info(request):
params=""
requestheader=reques.META.get('CONTENT_TYPE')
if request.method == 'POST':
if requestheader=='application/x-www-form-urlencoded':
params=reques.POST
elif requestheader='application/json':
params=json.loads(params)
else:
print('error header')
return HttpResponse(json.dumps(params))
else:
print('error method')
#整合get,post为一个接口
def service(request):
params={}
request_header=request.META.get('CONTENT_TYPE')
if request.method == "GET":
for k,v in request.GET.items():
params[k] = v
elif request.method == "POST":
if request_header=='application/x-www-form-urlencoded':
params = request.POST
elif request.header=='application/josn':
params = json.loads(params)
else:
return HttpResponse("error headers")
else:
return HttpResponse("error methods")
retrun HttpResponse(json.dumps(params))
def excu_Cookie(cookies):
message = "提交订单--Cookies是"
return HttpResponse(message + cookies)