#自写
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"。
然后