django写接口(api)

#自写

django写接口(api)

在django网页框架里简单写一个从数据库里查询数据并且返回的接口

#urls.py文件
from django.contrib import admin
from django.urls import path,re_path
from myapp import views
from django.views.static import serve
urlpatterns = [
    path(r'get_js_data/',views.get_data),#返回数据的接口
]

#views.py文件
from django.shortcuts import render,redirect
from .models import Student		#要查询的数据库model
import json
from django.http import HttpResponse
from django.core.exceptions import ObjectDoesNotExist
def get_data(request):
    new_data=Student.objects.all().order_by("-id")[:800]#查询最新的800条数据数据
                                                                                       #Student是要查询的数据库model

    light=[]
    hum=[]
    temp=[]#创建中间容器

    for i in new_data:
        temp.insert(0,i.temp)
        hum.insert(0,i.hum)
        light.insert(0,i.light)#将数据放入容器

    #判断是不是“POST”请求,post更安全如果想在网页输入返回数据
    #将"POST"改成"GET"
    if request.method == "POST":
        #将数据打包返回
        return HttpResponse(json.dumps({
            "get_temp":temp,
            "get_hum":hum,
            "get_light":light,
        }))

要注意本文里的数据库表是Student,是你在models.py里定义好的。
想在网页输入返回数据将"POST"改成"GET"。
然后
django返回数据接口

  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值