Django 后台解析请求数据的方法



d
from django.shortcuts import render
from django.http import request, response, HttpRequest, HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.csrf import csrf_exempt
import sys
import os
import json
import requests

def person(request):
    # application/json
    if request.method == 'POST':
        # 拿取数据:json发送post时,数据是在body里
        data = json.loads(request.body.decode())
        # 此时 data 是一个 dict
        res = '你提交的内容是【%s】' % data['content']
        result = {'data': res}
        return HttpResponse(json.dumps(result), content_type="application/json")
    else:
        return HttpResponse('请求类型错误')


def student(request):
    # form表单
    if request.method == 'POST':
        username = request.POST.get('user')
        age = request.POST.get('age')
        return HttpResponse('你输入的用户姓名是:%s, 年龄是:%s' % (username, age))
    elif request.method == 'GET':
        username = request.GET.get('user')
        age = request.GET.get('age')
        return HttpResponse('你输入的用户姓名是:%s, 年龄是:%s' % (username, age))
    else:
        return HttpResponse('没有拿取到数据噢')

  


posted @ 2020-04-17 09:47  breakcircle  阅读(426)  评论(0编辑  收藏  举报