超越村后端开发(4:API开发)

时间:2023-01-16 13:49:03

1.users相关的api开发

1.在settings中添加APPID,SECRET

超越村后端开发(4:API开发)

2.在apps/users/views.py内:

from chaoyuecun.settings import APPID,SECRET
import urllib.request
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.renderers import JSONRenderer,BrowsableAPIRenderer
from .serializers import WxUsersAreaModelSerializer
import json
from .models import WxUsers
import hashlib,time

from datetime import datetime
# Create your views here.

class WxLoginView(APIView):
    """微信用户无感登录"""
    renderer_classes = [JSONRenderer]  # 渲染器

    def get(self,request):
        code=request.GET.get('code')
        # print(request.GET)
        if code:
            # 用前端发过来的code把openid和session_key兑换过来
            url="https://api.weixin.qq.com/sns/jscode2session?appid="+APPID+"&secret="+SECRET+"&js_code="+code+"&grant_type=authorization_code"
            res=urllib.request.urlopen(url)
            content=res.read().decode()
            obj=json.loads(content)
            openid=obj["openid"]
            # print(openid)
            if openid:
                #生成token,加密
                i=int(time.time())
                s=str(i)
                sha= hashlib.sha1()
                sha.update((openid+s).encode('utf-8'))
                token=sha.hexdigest()
                # print(token)
                #查看以前此用户是否登陆过
                wxuser = WxUsers.objects.filter(open_id=openid).first()
                if wxuser:
                    #如果登录过,就将token值更新
                    wxuser.token = token
                    #更新最后登录时间
                    wxuser.last_login_time=datetime.now()
                    wxuser.save()
                else:
                    #如果没登录过,就生成用户,并且赋值token
                    wxuser=WxUsers()
                    wxuser.open_id=openid
                    wxuser.token=token
                    wxuser.save()
                # 将token信息返回
                res={','data':{'code':'登录成功','token':token}}
            else:
                res={','data':{'code':'登录失败','msg':'未收到openid'}}
        else:
            res = {', 'data':{'code':'登录失败','msg':'未收到code'}}
        # return Response(json.dumps(res, ensure_ascii=False))
        return Response(res)

class GetUserInfoView(APIView):
    """获取用户信息"""
    renderer_classes = [JSONRenderer]  # 渲染器

    def get(self,request):
        token=request._request.GET.get('token','')
        if token:
            # 根据token寻找对应的微信用户
            wxuser=WxUsers.objects.filter(token=token).first()
            if wxuser:
                #获取用户昵称、用户头像地址、用户市、用户性别
                nickName=request._request.GET.get('nickName','')
                avatarUrl=request._request.GET.get('avatarUrl','')
                gender=request._request.GET.get('gender','')
                city=request._request.GET.get('city','')
                #因为gender有可能是0,0在python里属于False,所以不能用来and验证
                if nickName and avatarUrl and city:
                    wxuser.nickName=nickName
                    wxuser.avatarUrl=avatarUrl
                    wxuser.gender=gender
                    wxuser.city=city
                    wxuser.save()
                    res={', 'data': {'code': '获取用户信息成功', 'msg': ''}}
                else:
                    res = {', 'data': {'code': '获取用户信息失败', 'msg': '用户信息不全'}}
            else:
                res = {', 'data': {'code':'获取用户信息失败','msg':'token不正确'}}
        else:
            res = {', 'data': {'code':'获取用户信息失败','msg':'未收到token'}}
        return Response(res)

class GetAreaView(APIView):
    """
    获取用户经纬度
    """
    def get(self,request):
        token=request._request.GET.get('token','')
        longitude = request._request.GET.get('longitude', '')
        latitude = request._request.GET.get('latitude', '')
        if token:
            wxuser=WxUsers.objects.filter(token=token).first()
            if wxuser:
                if longitude and latitude:
                    wxuser.longitude=longitude
                    wxuser.latitude=latitude
                    wxuser.save()
                    res = {', 'data': {'code': '获取用户经纬度成功', 'msg': ''}}
                else:
                    res= {', 'data':{'code':'获取用户经纬度失败','msg':'未收到用户经纬度'}}
            else:
                res = {', 'data': {'code': '获取用户经纬度失败', 'msg': '用户token错误'}}
        else:
            res = {', 'data': {'code': '获取用户经纬度失败', 'msg': '未收到用户token'}}
        return Response(res)

class GetAllWxUserLocationView(APIView):
    """获取所有微信用户经纬度"""
    def get(self,request):
        allwxuserlocation_list=WxUsers.objects.all()
        re=WxUsersAreaModelSerializer(allwxuserlocation_list,many=True)
        return Response(re.data)

3.在urls.py内:

因为并没有很多api,所以路由就不分别放在不同的app下了

#……
from users.views import WxLoginView,GetUserInfoView,GetAreaView,GetAllWxUserLocationView

urlpatterns = [
#……
    path('login/',WxLoginView.as_view()),
    path('getuserinfo/',GetUserInfoView.as_view()),
    path('getarea/',GetAreaView.as_view()),
    path('getalllocation/',GetAllWxUserLocationView.as_view())
]

4.在小程序端测试users相关的api

1.在index.vue中:

<template>
  <div>
    {{title}}
    <button open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 获取用户信息权限 </button>
    <div>token:02cfd6476d002081c0475d4644a2a53c8766205c</div>
  </div>
</template>
<script>
export default {
  data () {
    return {
      title: '第一次打开小程序的首页'
    }
  },
  methods: {
  //用户api测试
    //无感登录
    Login(){
      wx.login({
        success(res) {
          if (res.code) {
            // 发起网络请求
              wx.request({
                url: 'http://127.0.0.1:8000/login/',
                data: {
                  code: res.code
                },
                success(res) {
                  console.log(res.data)
                  if(res.data.status==="200"){
                    wx.setStorageSync('token', res.data.data.token)
                  }
                  console.log('token:',wx.getStorageSync('token') || [])
                }
              })
          } else {
            console.log('登录失败!' + res.errMsg)
          }
        }
      })
    },

    //获取用户信息,传到后端
    getSetting1(){
      wx.getSetting({
        success: function(res){
          if (res.authSetting['scope.userInfo']) {
            wx.getUserInfo({
              success: function(res) {
                console.log(res.userInfo)
                //用户已经授权过
                console.log('用户已经授权过')

                //向后端发送用户信息(昵称、性别、头像地址、所在城市)
                var token=wx.getStorageSync('token') || []
                wx.request({
                  url: 'http://127.0.0.1:8000/getuserinfo/',
                  data:{
                    token:token,
                    nickName:res.userInfo.nickName,
                    city:res.userInfo.city,
                    avatarUrl:res.userInfo.avatarUrl,
                    gender:res.userInfo.gender
                  },
                  success(res) {
                    console.log(res.data)
                  }
                })
                //……………………………………………………………………

              }
            })
          }else{
            console.log('用户还未授权过')
            //没授权则自动关闭小程序
          }
        }
      })
    },

    //获取地理位置
    getPermission(){

      wx.getSetting({
        success(res) {
          console.log(res.authSetting)
          if(res.authSetting['scope.userLocation']===true){
            console.log('已经授权获取地理位置')
            wx.getLocation({
              type: 'wgs84',
              success(res) {
                console.log(res)
                var token=wx.getStorageSync('token') || []
                wx.request({
                  url:'http://127.0.0.1:8000/getarea/',
                  data:{
                    token:token,
                    latitude:res.latitude,
                    longitude:res.longitude
                  },
                  success(res){
                    console.log(res.data)
                  }
                })

              }
            })

          }
          else{
            console.log('未授权获取地理位置')
            wx.authorize({
              // 如果没授权过,弹出授权框
              scope: 'scope.userLocation',
              success(){
                // 用户点击了授权
                console.log('授权成功!')
              },
              fail(){
                console.log('拒绝授权')
              }
            })
          }

        }
      })

    },

    //获取所有用户地理位置
    getAll(){
      wx.request({
        url:'http://127.0.0.1:8000/getalllocation/',
        success(res){
          console.log(res.data)
        }
      })
    },

  },
  onShow(){
    // this.getPermission()
  },

  created () {
    // this.Login()

    // this.getSetting1()
    // this.getAll()
  }
}
</script>
<style scoped>
</style>

2.效果图:

超越村后端开发(4:API开发)

2.wish相关的api开发

1.新发布愿望的api开发

1.在apps/wish/views.py中:

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.renderers import JSONRenderer,BrowsableAPIRenderer
from users.models import WxUsers
from .models import Wish,News,Images
from .serializers import WishModelSerializer,NewsModelSerializer,ImagesModelSerializer
from datetime import datetime
# Create your views here.

class MakeNewWishView(APIView):
    """发布愿望"""
    renderer_classes = [JSONRenderer]  # 渲染器
    def post(self,request):
        token = request._request.POST.get('token', '')
        if token:
            # 根据token寻找对应的微信用户
            wxuser = WxUsers.objects.filter(token=token).first()
            if wxuser:
                timestamp=request._request.POST.get('timestamp', '')
                wish=request._request.POST.get('wish', '')
                if timestamp and wish:
                    t = datetime.fromtimestamp(int(timestamp) / 1000)
                    newwish=Wish()
                    newwish.wxuser=wxuser
                    newwish.content=wish
                    newwish.end_time=t
                    newwish.save()
                    res = {', 'data': {'code': '发布成功', 'msg': ''}}
                else:
                    res = {', 'data': {'code': '发布失败', 'msg': '提交数据不足'}}
            else:
                res = {', 'data': {'code': '发布失败', 'msg': 'token不正确'}}
        else:
            res = {', 'data': {'code': '发布失败', 'msg': '未收到token'}}
        return Response(res)

2.在urls.py中:

from wish.views import MakeNewWishView

urlpatterns = [
#……
    path('makenewwish/',MakeNewWishView.as_view())
]

3.在小程序端测试:

1.引入vant-ui的时间选择器组件

2.在index.vue中:

<template>
  <div>
    {{title}}
    <div>token:02cfd6476d002081c0475d4644a2a53c8766205c</div>
    <van-datetime-picker type="datetime" :loading="loading" :value="currentDate1" :min-date="minDate" @confirm="onChange"/>
    愿望:<input type="text" v-model="wish">
    <button @click="Makewish">提交</button>
  </div>
</template>
<script>
export default {
  data () {
    return {
      title: '第一次打开小程序的首页',

      loading: false,
      currentDate1: new Date(2019, 4, 1).getTime(),
      minDate: new Date(2019, 3, 25).getTime(),

      timestamp:0,

      wish:''

    }
  },
  methods: {
    onChange ({mp}) {
        console.log(mp.detail)
        this.timestamp=mp.detail
      },

    Makewish(){
      wx.request({
        url:'http://127.0.0.1:8000/makenewwish/',
        data:{
          token:'02cfd6476d002081c0475d4644a2a53c8766205c',
          wish:this.wish,
          timestamp:this.timestamp
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        method:'POST',
        success(res){
          console.log(res.data)
        }
      })
    }

  },
  created () {

  }
}
</script>
<style scoped>
</style>

3.测试过程:运行项目,然后选择时间,然后点击【确认】按钮,然后再编辑愿望,再点击【提交】按钮

4.效果图:

超越村后端开发(4:API开发)

5.多生产几条新愿望,以备后面使用。

2.获取愿望列表api的开发

注意:这里获取的愿望,都是状态在‘进行中’的愿望。

1.在apps/wish/views.py中:

class GetAllWishView(APIView):
    """获取所有在进行中的愿望"""
    renderer_classes = [JSONRenderer]  # 渲染器
    def get(self,request):
        wish_list=Wish.objects.filter(status=')
        re=WishModelSerializer(wish_list,many=True)
        return Response(re.data)

2.在urls.py中:

#……
from wish.views import GetAllWishView
urlpatterns = [
#……
    path('getallwish/',GetAllWishView.as_view())
]

3.小程序端测试

1.index.vue:

<template>
  <div>
    {{title}}
    <div>token:02cfd6476d002081c0475d4644a2a53c8766205c</div>

  </div>
</template>
<script>
export default {
  data () {
    return {
      title: '第一次打开小程序的首页'
    }
  },
  methods: {
    getAllwish(){
      wx.request({
        url: 'http://127.0.0.1:8000/getallwish/',
        success(res) {
          console.log(res.data)
        }
      })
    }

  },
  created () {
    this.getAllwish()
  }
}
</script>
<style scoped>
</style>

2.运行项目,效果图

超越村后端开发(4:API开发)

3.获取新闻的api开发

1.通过xadmin,使用管路员账号,先创造一些新闻数据,以及一些新闻图片。

超越村后端开发(4:API开发)         超越村后端开发(4:API开发)

2.在apps/wish/views.py内开发获取新闻列表、新闻详情、新闻图片类:

class GetNewsListView(APIView):
    """获取新闻列表"""
    renderer_classes = [JSONRenderer]  # 渲染器
    def get(self,request):
        news_list=News.objects.all().order_by('-add_time')
        re=NewsModelSerializer(news_list,many=True)
        return Response(re.data)

class GetNewsDetailView(APIView):
    """获取单条新闻"""
    renderer_classes = [JSONRenderer]  # 渲染器
    def get(self, request):
        id=request._request.GET.get('id','')
        if id:
            news=News.objects.filter(id=id).first()
            if news:
                re=NewsModelSerializer(news)
                return Response(re.data)
            else:
                res = {', 'data': {'code': '获取失败', 'msg': '没有此条新闻'}}
        else:
            res = {', 'data': {'code': '获取失败', 'msg': '未收到新闻id'}}
        return Response(res)

class GetNewsImagesView(APIView):
    """获取新闻图片"""
    renderer_classes = [JSONRenderer]  # 渲染器
    def get(self, request):
        id=request._request.GET.get('id','')
        if id:
            news=News.objects.filter(id=id).first()
            if news:
                images_list=Images.objects.filter(news=news)
                re=ImagesModelSerializer(images_list,many=True)
                return Response(re.data)
            else:
                res = {', 'data': {'code': '获取失败', 'msg': '没有此条新闻'}}
        else:
            res = {', 'data': {'code': '获取失败', 'msg': '未收到新闻id'}}
        return Response(res)

3.在urls.py内配置路由:

#……
from wish.views import MakeNewWishView,GetAllWishView,GetNewsDetailView,GetNewsImagesView,GetNewsListView

urlpatterns = [
#……
    path('getnewsdetail/',GetNewsDetailView.as_view()),
    path('getnewsImages/',GetNewsImagesView.as_view()),
    path('getnewslist/',GetNewsListView.as_view())
]

4.小程序端测试:

1.index.vue内代中:

<template>
  <div>
    {{title}}
    <div>token:02cfd6476d002081c0475d4644a2a53c8766205c</div>

  </div>
</template>
<script>
export default {
  data () {
    return {
      title: '第一次打开小程序的首页'
    }
  },
  methods: {
    getNewsDetail(){
      wx.request({
        url: 'http://127.0.0.1:8000/getnewsdetail/',
        data:{
          id:1
        },
        success(res) {
          console.log(res.data)
        }
      })
    },
    getNewsImages(){
      wx.request({
        url: 'http://127.0.0.1:8000/getnewsImages/',
        data:{
          id:1
        },
        success(res) {
          console.log(res.data)
        }
      })
    },
    getNewsList(){
      wx.request({
        url: 'http://127.0.0.1:8000/getnewslist/',
        success(res) {
          console.log(res.data)
        }
      })
    }

  },
  created () {
    this.getNewsDetail()
    this.getNewsImages()
    this.getNewsList()
  }
}
</script>
<style scoped>
</style>

2.效果图

超越村后端开发(4:API开发)

3.user_operation相关的开发

1.开发发布对愿望的评论(也就是消息),获取消息列表,读特定消息,删除特定消息的api

1.通过后台先在【评论表】内手动添加几条模拟消息

2.在apps/user_operation/views.py中:

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.renderers import JSONRenderer,BrowsableAPIRenderer
from users.models import WxUsers
from wish.models import Wish
from .models import Message,Pick,Share,Notice
from .serializers import MessageModelSerializer,PickModelSerializer,ShareModelSerializer,NoticeModelSerializer

# Create your views here.

class MakeMessageView(APIView):
    """发布愿望的评论,获取愿望评论列表"""
    renderer_classes = [JSONRenderer]  # 渲染器

    def post(self,request):
        token = request._request.POST.get('token', '')
        if token:
            # 根据token寻找对应的微信用户
            wxuser = WxUsers.objects.filter(token=token).first()
            if wxuser:
                wish_id=request._request.POST.get('wish_id', '')
                content=request._request.POST.get('content', '')
                if wish_id and content:
                    wish=Wish.objects.filter(id=wish_id).first()
                    if wish:
                        message=Message()
                        message.user_send=wxuser
                        message.user_receive=wish.wxuser
                        message.wish=wish
                        message.content=content
                        message.save()
                        res = {', 'data': {'code': '发布成功', 'msg': ''}}
                    else:
                        res = {', 'data': {'code': '发布失败', 'msg': '没有这条愿望了'}}
                else:
                    res = {', 'data': {'code': '发布失败', 'msg': '提交数据不足'}}
            else:
                res = {', 'data': {'code': '发布失败', 'msg': 'token不正确'}}
        else:
            res = {', 'data': {'code': '发布失败', 'msg': '未收到token'}}
        return Response(res)

    def get(self,request):
        """获取用户收到所有消息"""
        token = request._request.GET.get('token', '')
        if token:
            # 根据token寻找对应的微信用户
            wxuser = WxUsers.objects.filter(token=token).first()
            if wxuser:
                message_list=Message.objects.filter(user_receive=wxuser).order_by('-add_time')
                re=MessageModelSerializer(message_list,many=True)
                return Response(re.data)
            else:
                res = {', 'data': {'code': '获取失败', 'msg': 'token不正确'}}
        else:
            res = {', 'data': {'code': '获取失败', 'msg': '未收到token'}}
        return Response(res)

class ReadMessageView(APIView):
    """查看和删除评论"""
    renderer_classes = [JSONRenderer]  # 渲染器
    def get(self,request):
        token = request._request.GET.get('token', '')
        if token:
            # 根据token寻找对应的微信用户
            wxuser = WxUsers.objects.filter(token=token).first()
            if wxuser:
                message_id=request._request.GET.get('message_id', '')
                if message_id:
                    message=Message.objects.filter(id=message_id).first()
                    if message:
                        message.is_read=True
                        message.save()
                        res = {', 'data': {'code': '获取成功', 'msg': '指定id评论为已读'}}
                    else:
                        res = {', 'data': {'code': '获取失败', 'msg': '未找到指定id对应评论'}}
                else:
                    res = {', 'data': {'code': '获取失败', 'msg': '未收到评论id'}}
            else:
                res = {', 'data': {'code': '获取失败', 'msg': 'token不正确'}}
        else:
            res = {', 'data': {'code': '获取失败', 'msg': '未收到token'}}
        return Response(res)

    def post(self,request):
        token = request._request.POST.get('token', '')
        if token:
            # 根据token寻找对应的微信用户
            wxuser = WxUsers.objects.filter(token=token).first()
            if wxuser:
                message_id=request._request.POST.get('message_id', '')
                if message_id:
                    message=Message.objects.filter(id=message_id).delete()
                    res = {', 'data': {'code': '操作成功', 'msg': '指定id评论为已删除'}}
                else:
                    res = {', 'data': {'code': '操作失败', 'msg': '未收到评论id'}}
            else:
                res = {', 'data': {'code': '操作失败', 'msg': 'token不正确'}}
        else:
            res = {', 'data': {'code': '操作失败', 'msg': '未收到token'}}
        return Response(res)

3.在urls.py内添加路由:

#……
from user_operation.views import MakeMessageView,ReadMessageView

urlpatterns = [
    #……
    path('makemessage/',MakeMessageView.as_view()),
    path('readmessage/',ReadMessageView.as_view())
]

4.在小程序端调试:

1.在index.vue中:

<template>
  <div>
    {{title}}
    <div>token:02cfd6476d002081c0475d4644a2a53c8766205c</div>

  </div>
</template>
<script>
export default {
  data () {
    return {
      title: '第一次打开小程序的首页'
    }
  },
  methods: {
    MakeMessage(){
       wx.request({
        url:'http://127.0.0.1:8000/makemessage/',
        data:{
          token:'02cfd6476d002081c0475d4644a2a53c8766205c',
          wish_id:1,
          content:'2222这是一条有可能友好又有可能不友好的评论'
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        method:'POST',
        success(res){
          console.log(res.data)
        }
      })
    },
    GetMessage(){
      wx.request({
        url:'http://127.0.0.1:8000/makemessage/',
        data:{
          token:'02cfd6476d002081c0475d4644a2a53c8766205c'
        },
        success(res){
          console.log(res.data)
        }
      })
    },
    ReadMessage(){
      wx.request({
        url:'http://127.0.0.1:8000/readmessage/',
        data:{
          token:'02cfd6476d002081c0475d4644a2a53c8766205c',
          message_id:1
        },
        success(res){
          console.log(res.data)
        }
      })
    },
    DelMessage(){
      wx.request({
        url:'http://127.0.0.1:8000/readmessage/',
        data:{
          token:'02cfd6476d002081c0475d4644a2a53c8766205c',
          message_id:2
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        method:'POST',
        success(res){
          console.log(res.data)
        }
      })
    }

  },
  created () {
    // this.MakeMessage()
    // this.GetMessage()
    this.ReadMessage()
    this.DelMessage()

  }
}
</script>
<style scoped>
</style>

2.效果图:

超越村后端开发(4:API开发)

2.开发 点赞指定愿望、获取指定愿望点赞数、分享指定愿望、获取指定愿望被分享数 的api

1.在apps/user_operation/views.py中:

class PickWishView(APIView):
    """get获取点赞数,post点赞/取消指定愿望点赞"""
    renderer_classes = [JSONRenderer]  # 渲染器
    def post(self,request):
        token = request._request.POST.get('token', '')
        if token:
            # 根据token寻找对应的微信用户
            wxuser = WxUsers.objects.filter(token=token).first()
            if wxuser:
                wish_id=request._request.POST.get('wish_id', '')
                if wish_id:
                    wish=Wish.objects.filter(id=wish_id).first()
                    if wish:
                        pick=Pick.objects.filter(wish=wish,user=wxuser).first()
                        if pick:
                            #如果有点赞记录,则删除
                            pick.delete()
                        else:
                            new_pick=Pick()
                            new_pick.user=wxuser
                            new_pick.wish=wish
                            new_pick.save()
                        res = {', 'data': {'code': '操作成功', 'msg': ''}}
                    else:
                        res = {', 'data': {'code': '操作失败', 'msg': '未找到指定id对应的愿望'}}
                else:
                    res = {', 'data': {'code': '操作失败', 'msg': '未收到愿望id'}}
            else:
                res = {', 'data': {'code': '操作失败', 'msg': 'token不正确'}}
        else:
            res = {', 'data': {'code': '操作失败', 'msg': '未收到token'}}
        return Response(res)

    def get(self,request):
        wish_id=request._request.GET.get('wish_id', '')
        if wish_id:
            wish=Wish.objects.filter(id=wish_id).first()
            if wish:
                nums=Pick.objects.filter(wish=wish).count()
                res = {', 'data': {'code': '获取成功', 'nums': nums}}
            else:
                res = {', 'data': {'code': '获取失败', 'msg': '未找到指定id对应的愿望'}}
        else:
            res = {', 'data': {'code': '获取失败', 'msg': '未收到愿望id'}}
        return Response(res)

class ShareWishView(APIView):
    """get获取愿望被分享数,post分享指定愿望"""
    renderer_classes = [JSONRenderer]  # 渲染器
    def get(self,request):
        wish_id=request._request.GET.get('wish_id', '')
        if wish_id:
            wish=Wish.objects.filter(id=wish_id).first()
            if wish:
                nums=Share.objects.filter(wish=wish).count()
                res = {', 'data': {'code': '获取成功', 'nums': nums}}
            else:
                res = {', 'data': {'code': '获取失败', 'msg': '未找到指定id对应的愿望'}}
        else:
            res = {', 'data': {'code': '获取失败', 'msg': '未收到愿望id'}}
        return Response(res)
    def post(self,request):
        token = request._request.POST.get('token', '')
        if token:
            # 根据token寻找对应的微信用户
            wxuser = WxUsers.objects.filter(token=token).first()
            if wxuser:
                wish_id=request._request.POST.get('wish_id', '')
                if wish_id:
                    wish=Wish.objects.filter(id=wish_id).first()
                    if wish:
                        new_share=Share()
                        new_share.user=wxuser
                        new_share.wish=wish
                        new_share.save()
                        res = {', 'data': {'code': '操作成功', 'msg': ''}}
                    else:
                        res = {', 'data': {'code': '操作失败', 'msg': '未找到指定id对应的愿望'}}
                else:
                    res = {', 'data': {'code': '操作失败', 'msg': '未收到愿望id'}}
            else:
                res = {', 'data': {'code': '操作失败', 'msg': 'token不正确'}}
        else:
            res = {', 'data': {'code': '操作失败', 'msg': '未收到token'}}
        return Response(res)

2.在urls.py中配置路由:

#……
from user_operation.views import PickWishView,ShareWishView

urlpatterns = [
    #……
    path('pickwish/',PickWishView.as_view()),
    path('sharewish/',ShareWishView.as_view())
]

3.在小程序端调试

1.在index.vue中

<template>
  <div>
    {{title}}
    <div>token:02cfd6476d002081c0475d4644a2a53c8766205c</div>

  </div>
</template>
<script>
export default {
  data () {
    return {
      title: '第一次打开小程序的首页'
    }
  },
  methods: {
    PickWish(){
      wx.request({
        url:'http://127.0.0.1:8000/pickwish/',
        data:{
          token:'02cfd6476d002081c0475d4644a2a53c8766205c',
          wish_id:1
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        method:'POST',
        success(res){
          console.log(res.data)
        }
      })
    },
    GetWishPickNum(){
      wx.request({
        url:'http://127.0.0.1:8000/pickwish/',
        data:{
          wish_id:1
        },
        success(res){
          console.log(res.data)
        }
      })
    },
    ShareWish(){
      wx.request({
        url:'http://127.0.0.1:8000/sharewish/',
        data:{
          token:'02cfd6476d002081c0475d4644a2a53c8766205c',
          wish_id:1
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        method:'POST',
        success(res){
          console.log(res.data)
        }
      })
    },
    GetWishShareNum(){
      wx.request({
        url:'http://127.0.0.1:8000/sharewish/',
        data:{
          wish_id:1
        },
        success(res){
          console.log(res.data)
        }
      })
    }

  },
  created () {
    // this.PickWish()
    // this.GetWishPickNum()
    this.ShareWish()
    this.GetWishShareNum()

  }
}
</script>
<style scoped>
</style>

2.效果图:

超越村后端开发(4:API开发)

3.开发获取最新公告的api

1.通过xadmin在【系统通知表】增加两条数据记录

超越村后端开发(4:API开发)

2.在apps/user_operation/views.py中

class GetNoticeView(APIView):
    '''get获取最新公告'''
    renderer_classes = [JSONRenderer]  # 渲染器
    def get(self, request):
        notice=Notice.objects.all().last()
        re=NoticeModelSerializer(notice)
        return Response(re.data)

3.在urls.py中配置路由:

#……
from user_operation.views import GetNoticeView

urlpatterns = [
    # ……
    path('getnotice/',GetNoticeView.as_view())
]

4.在小程序端测试:

1.在index.vue中

<template>
  <div>
    {{title}}
    <div>token:02cfd6476d002081c0475d4644a2a53c8766205c</div>

  </div>
</template>
<script>
export default {
  data () {
    return {
      title: '第一次打开小程序的首页'
    }
  },
  methods: {
    getNotice(){
      wx.request({
        url:'http://127.0.0.1:8000/getnotice/',
        success(res){
          console.log(res.data)
        }
      })
    }

  },
  created () {
    this.getNotice()
  }
}
</script>
<style scoped>
</style>

2.效果图:只会显示最新的 公告

超越村后端开发(4:API开发)

4.开发用户对自己的愿望进行操作的api

1.在apps/use_operation/views.py中:

from wish.serializers import WishModelSerializer

class MyWishView(APIView):
    """
    get 获取我的愿望(包括正在进行的、放弃的,达成的)
    post flag=1 实现愿望,flag=2 放弃愿望 ,flag=3删除愿望
    """
    renderer_classes = [JSONRenderer]  # 渲染器
    def get(self,request):
        token = request._request.GET.get('token', '')
        if token:
            # 根据token寻找对应的微信用户
            wxuser = WxUsers.objects.filter(token=token).first()
            if wxuser:
                wish_list=Wish.objects.filter(wxuser=wxuser).all()
                re=WishModelSerializer(wish_list,many=True)
                return Response(re.data)
            else:
                res = {', 'data': {'code': '获取失败', 'msg': 'token不正确'}}
        else:
            res = {', 'data': {'code': '获取失败', 'msg': '未收到token'}}
        return Response(res)
    def post(self,request):
        token = request._request.POST.get('token', '')
        if token:
            # 根据token寻找对应的微信用户
            wxuser = WxUsers.objects.filter(token=token).first()
            if wxuser:
                wish_id=request._request.POST.get('wish_id', '')
                if wish_id:
                    wish=Wish.objects.filter(id=wish_id).first()
                    if wish:
                        flag=request._request.POST.get('flag', '')
                        ':
                            wish.status='
                            wish.save()
                            res = {', 'data': {'code': '操作成功', 'msg': ''}}
                        ':
                            wish.status = '
                            wish.save()
                            res = {', 'data': {'code': '操作成功', 'msg': ''}}
                        ':
                            wish.delete()
                            res = {', 'data': {'code': '操作成功', 'msg': ''}}
                        else:
                            res = {', 'data': {'code': '操作失败', 'msg': '未收到flag'}}
                    else:
                        res = {', 'data': {'code': '操作失败', 'msg': '未找到指定id对应的愿望'}}
                else:
                    res = {', 'data': {'code': '操作失败', 'msg': '未收到愿望id'}}
            else:
                res = {', 'data': {'code': '操作失败', 'msg': 'token不正确'}}
        else:
            res = {', 'data': {'code': '操作失败', 'msg': '未收到token'}}
        return Response(res)

2.在urls.py中配置:

#……
from user_operation.views import MyWishView

urlpatterns = [
    # ……
    path('mywish/',MyWishView.as_view())
]

3.小程序端调试

1.在index.vue中:

<template>
  <div>
    {{title}}
    <div>token:02cfd6476d002081c0475d4644a2a53c8766205c</div>

  </div>
</template>
<script>
export default {
  data () {
    return {
      title: '第一次打开小程序的首页'
    }
  },
  methods: {
    //获取个人所有愿望
    GetMyWish(){
      wx.request({
        url:'http://127.0.0.1:8000/mywish/',
        data:{
          token:'02cfd6476d002081c0475d4644a2a53c8766205c'
        },
        success(res){
          console.log(res.data)
        }
      })
    },
    //愿望实现了
    BecomeWish(){

      wx.request({
        url:'http://127.0.0.1:8000/mywish/',
        data:{
          token:'02cfd6476d002081c0475d4644a2a53c8766205c',
          wish_id:1,
          flag:1
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        method:'POST',
        success(res){
          console.log(res.data)
        }
      })
    },

    //放弃愿望
    GiveUpWish(){
      wx.request({
        url:'http://127.0.0.1:8000/mywish/',
        data:{
          token:'02cfd6476d002081c0475d4644a2a53c8766205c',
          wish_id:1,
          flag:2
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        method:'POST',
        success(res){
          console.log(res.data)
        }
      })
    },

    //删除愿望
    DelWish(){
      wx.request({
        url:'http://127.0.0.1:8000/mywish/',
        data:{
          token:'02cfd6476d002081c0475d4644a2a53c8766205c',
          wish_id:1,
          flag:3
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        method:'POST',
        success(res){
          console.log(res.data)
        }
      })
    }

  },
  created () {
    // this.GetMyWish()
    // this.BecomeWish()
    // this.GiveUpWish()
    this.DelWish()
  }
}
</script>
<style scoped>
</style>

2.效果图:

超越村后端开发(4:API开发)

5.开发获取指定愿望的评论数api

1.在apps/user_operation/views.py中:

class GetWishMessageView(APIView):
    """get 获取指定愿望的评论数"""
    renderer_classes = [JSONRenderer]  # 渲染器
    def get(self,request):
        wish_id=request._request.GET.get('wish_id', '')
        if wish_id:
            wish=Wish.objects.filter(id=wish_id).first()
            if wish:
                nums=Message.objects.filter(wish=wish).count()
                res = {', 'data': {'code': '获取成功', 'nums': nums}}
            else:
                res = {', 'data': {'code': '获取失败', 'msg': '未找到指定id对应的愿望'}}
        else:
            res = {', 'data': {'code': '获取失败', 'msg': '未收到愿望id'}}
        return Response(res)

2.在urls.py中配置:

#……
from user_operation.views importGetWishMessageView

urlpatterns = [
    # ……
    path('getwishmessage/',GetWishMessageView.as_view())
]

3.小程序端调试:

1.index.vue中:

<template>
  <div>
    {{title}}
    <div>token:02cfd6476d002081c0475d4644a2a53c8766205c</div>

  </div>
</template>
<script>
export default {
  data () {
    return {
      title: '第一次打开小程序的首页'
    }
  },
  methods: {
   GetWishMsgNum(){
    wx.request({
      url:'http://127.0.0.1:8000/getwishmessage/',
      data:{
        wish_id:2,
      },
      success(res){
        console.log(res.data)
      }
    })
   }

  },
  created () {
    this.GetWishMsgNum()
  }
}
</script>
<style scoped>
</style>

2.效果图

超越村后端开发(4:API开发)