Djangorestframework编写post接口

前提:已经有Django环境

一、安装 pip install djangorestframework

二、编写视图

  

import json
from django.shortcuts import render
import pymysql

from django.http import JsonResponse
from rest_framework.views import APIView
 
# 用djangorestframework创建post接口时需要继承APIView
class caseInfo(APIView):
    # 这里的方法名只能是post或者get等等请求方法的名称
    def post(self, requset):
        # 获取从前台通过form-data方式传来的参数值
        userCaseInfoId = requset.POST['userCaseInfoId']
        db = pymysql.connect("localhost", "root", "chen", "chen_test", charset='utf8')
        cursor = db.cursor()
        sql = "select * from userCaseInfo where id= %s" % userCaseInfoId
        cursor.execute(sql)
        results = cursor.fetchall()
        r=list(results[0])
        print r

        return JsonResponse({"code": 200, "msg": "success",
                             'data':{'id':r[0],'name':r[1],'caseCount':r[2],'passCount':r[3],'failCount':r[4]}},
                            content_type="application/json,charset=utf-8")

三、编写路由

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^caseInfoPost/', caseInfo.as_view()),
]

四、访问测试

  

获取从前台通过form-data格式传来的参数
原文地址:https://www.cnblogs.com/gcgc/p/10175329.html