文章目录

  • 3-1 Request&Response对象
  • 3-2 Django的RESTful URL设计
  • 3-3 实现个人助手功能清单发布
  • 3-4 实现图文消息
  • 3-5 Django类视图
  • 3-6 Django图文消息应用
  • 3-8 综合实践之生活服务-上
  • 3-8 综合实践之生活服务-下
  • 3-9 小程序股票、星座等功能实现
    • 实现技术
    • 获取小程序应用名字
  • 总结

3-1 Request&Response对象


3-2 Django的RESTful URL设计

3-3 实现个人助手功能清单发布

apis\views\menu.py 管理app
在app.js中定义全局接口地址

定义传递的应用数据

// pages/menu/menu.jsconst app = getApp()Page({/*** 页面的初始数据*/data: {grids: [{"name": "应用1"}, {"name": "应用2"}], // 九宫格内容},/*** 生命周期函数--监听页面加载*/onLoad: function(options) {this.updateMenuData()},/*** 请求后台,更新menu数据*/updateMenuData: function() {var that = thiswx.request({url: app.globalData.serverUrl + app.globalData.apiVersion + '/service/menu',success: function(res) {var menuData = res.data.dataconsole.log(menuData)that.setData({grids: menuData})}})},

页面渲染数据

3-4 实现图文消息

这里是采用本地存储

3-5 Django类视图

import json
from django.views import View
from django.http import HttpResponse, JsonResponsefrom utils.response import CommonResponseMixin
from thirdparty import juheclass WeatherView(View, CommonResponseMixin):def get(self, request):passdef post(self, request):data = []received_body = request.body.decode('utf-8')received_body = json.loads(received_body)print(received_body)cities = received_body.get('cities')for city in cities:result = juhe.weather(city.get('city'))result['city_info'] = citydata.append(result)response_data = self.wrap_json_response(data)return JsonResponse(data=response_data, safe=False)
class CommonResponseMixin(object):@classmethoddef wrap_json_response(cls, data=None, code=None, message=None):response = {}if not code:code = ReturnCode.SUCCESSif not message:message = ReturnCode.message(code)if data is not None:response['data'] = dataresponse['result_code'] = coderesponse['message'] = messagereturn response

3-6 Django图文消息应用

#!/usr/bin/python                                                                  import os
import hashlib
from django.views import View
from django.http import Http404, HttpResponse, FileResponse, JsonResponse
from backend import settings
from utils.response import ReturnCode, CommonResponseMixinclass ImageListView(View, CommonResponseMixin):def get(self, request):image_files = os.listdir(settings.IMAGES_DIR)response_data = []for image_file in image_files:response_data.append({'name': image_file,'md5': image_file[:-4]})response = self.wrap_json_response(data=response_data)return JsonResponse(data=response, safe=False)class ImageView(View, CommonResponseMixin):def get(self, request):md5 = request.GET.get('md5')imgfile = os.path.join(settings.IMAGES_DIR, md5 + '.jpg')print(imgfile)if os.path.exists(imgfile):data = open(imgfile, 'rb').read()# return HttpResponse(data, content_type='image/jpg')return FileResponse(open(imgfile, 'rb'), content_type='image/jpg')else:response = self.wrap_json_response(code=ReturnCode.RESOURCE_NOT_FOUND)return JsonResponse(data=response, safe=False)def post(self, request):files = request.FILESresponse_data = []for key, uploaded_file in files.items():print(key)print(uploaded_file)content = uploaded_file.read()md5 = hashlib.md5(content).hexdigest()path = os.path.join(settings.IMAGES_DIR, md5 + '.jpg')print(md5)with open(path, 'wb+') as f:f.write(content)response_data.append({'name': key,'md5': md5})response = self.wrap_json_response(data=response_data, code=ReturnCode.SUCCESS)return JsonResponse(data=response, safe=False)def delete(self, request):md5 = request.GET.get('md5')img_name = md5 + '.jpg'path = os.path.join(settings.IMAGES_DIR, img_name)if os.path.exists(path):os.remove(path)message = 'remove success.'else:message = 'file(%s) not found.' % img_nameresponse = self.wrap_json_response(code=ReturnCode.SUCCESS, message=message)return JsonResponse(data=response, safe=False)

3-8 综合实践之生活服务-上


pages/weather.js

// pages/weather/weather.jsconst app = getApp()const popularCities = [// {//   "province": "上海市",//   "city": "上海",//   "area": "徐汇区"// },{"province": "河南省","city": "郑州","area": "回族区"}
]Page({/*** 页面的初始数据*/data: {isAuthorized: false,weatherData: null},/*** 生命周期函数--监听页面加载*/onLoad: function(options) {this.updateWeatherData()},updateWeatherData: function() {wx.showLoading({title: '加载中',})var that = this;wx.request({url: app.globalData.serverUrl + app.globalData.apiVersion + '/service/weather',method: 'POST',header: {'content-type': 'application/json' // 默认值},// 查询的城市data: {cities: popularCities},success: function(res){console.log(res.data.data)that.setData({weatherData: res.data.data})wx.hideLoading()}})},/*** 页面相关事件处理函数--监听用户下拉动作*/onPullDownRefresh: function() {this.updateWeatherData()}
})

Django后端在上面

3-8 综合实践之生活服务-下


主要上图片备份,小程序前端back.js逻辑

const app = getApp()
const imageUrl = app.globalData.serverUrl + app.globalData.apiVersion + '/service/image'Page({data: {// 需要上传的图片needUploadFiles: [],// backupedFiles每个元素四个字段 name, md5, path, isDownloaded// 已下载的备份图片downloadedBackupedFiles: []},// 选择图片上传chooseImage: function(e) {var that = this;wx.chooseImage({sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有success: function(res) {// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片that.setData({needUploadFiles: that.data.needUploadFiles.concat(res.tempFilePaths)});}})},// 长按确认函数longTapConfirm: function(e) {var that = this// 上传视图的确认菜单var uploadConfirmList = ['取消上传']// 已备份图片列表视图的确认菜单var downloadedConfirmList = ['保存本地', '删除备份']if (e.currentTarget.dataset.type == 'UploadView') {var itemList = uploadConfirmList} else {var itemList = downloadedConfirmList}// 显示菜单wx.showActionSheet({itemList: itemList,success: function(res) {if (res.cancel) {return}// 上传视图的确认菜单逻辑if (e.currentTarget.dataset.type == 'UploadView' && res.tapIndex == 0){var imgId = e.currentTarget.dataset.idvar newNeedUploadFiles = that.data.needUploadFilesfor (var i = 0; i < newNeedUploadFiles.length; i ++){if(newNeedUploadFiles[i] == imgId){newNeedUploadFiles.splice(i, 1)}that.setData({needUploadFiles: newNeedUploadFiles})}}// 已备份图片列表视图的确认菜单逻辑if (e.currentTarget.dataset.type == 'DownloadedView' && res.tapIndex == 1){var imgIndex = e.currentTarget.dataset.indexvar imgItem = that.data.downloadedBackupedFiles[imgIndex]console.log(imgIndex)console.log(imgItem)console.log(that.data.downloadedBackupedFiles)var newDownloadedBackupedFiles = that.data.downloadedBackupedFilesnewDownloadedBackupedFiles.splice(imgIndex, 1)console.log(newDownloadedBackupedFiles)that.setData({// 删除图片本地downloadedBackupedFiles: newDownloadedBackupedFiles})// 删除图片远端that.deleteBackup(imgItem)}}});},// 上传图片文件uploadFiles: function() {var that = thisthat.setData({newBackupedFiles: []})for (var i = 0; i < this.data.needUploadFiles.length; i++) {var file = this.data.needUploadFiles[i]wx.uploadFile({url: app.globalData.serverUrl + app.globalData.apiVersion + '/service/image',filePath: file,name: 'test',success: function(res) {var resutData = JSON.parse(res.data)var imgData = resutData.data[0]var uploadedFile = {'name': imgData.name,'md5': imgData.md5,'path': '','isDownloaded': false}// 上传成功的保存到newBackupedFiles数组里that.downloadFile(uploadedFile)}})}wx.showToast({title: '上传成功',})// 清空等待上传的文件列表this.setData({needUploadFiles: []})},// 删除图片deleteBackup: function(imgItem){console.log('delete a backup file.' + imgItem)wx.request({url: imageUrl + '?md5=' + imgItem.md5,method: 'DELETE',success: function(res){console.log(res)wx.showToast({title: '删除成功',})}})},onLoad: function(){this.downloadAllFromRemote()},// 下载所有的已备份图片downloadAllFromRemote: function () {var that = this// 1. 请求后台获取已备份的图片列表wx.request({url: imageUrl + '/list',method: 'GET',success: function (res) {var imageList = res.data.datafor (var i = 0; i < imageList.length; i++) {// 2. 逐个调用downloadFile进行图片下载that.downloadFile(imageList[i])}}})},// 下载图片downloadFile: function (imgItem) {var that = thisvar downloadUrl = imageUrl + '?md5=' + imgItem.md5wx.downloadFile({url: downloadUrl,success: function (res) {var filepath = res.tempFilePathconsole.log(filepath)var newDownloadedBackupedFiles = that.data.downloadedBackupedFilesimgItem.path = filepathnewDownloadedBackupedFiles.unshift(imgItem)that.setData({downloadedBackupedFiles: newDownloadedBackupedFiles})console.log(newDownloadedBackupedFiles)}})},
});

3-9 小程序股票、星座等功能实现

实现技术

实现技术:后端主要是利用聚合数据api接口,来查询出相应APP应用API所获取的数据返回给小程序前端,具体的示例也可参考上面获取 天气的例子

def stock(market, code):'''沪深股票:param market: 上交所 = sh, 深交所 = sz:param code: 股票编号:return:'''key = ''api = 'http://web.juhe.cn:8080/finance/stock/hs'params = 'gid=%s&key=%s' % (market + code, key)url = api + '?' + paramsprint(url)response = requests.get(url=url, proxies=proxy.proxy())data = json.loads(response.text)data = data.get('result')[0].get('data')response = {'name': data.get('name'),'now_price': data.get('nowPri'),'today_min': data.get('todayMin'),'today_max': data.get('todayMax'),'start_price': data.get('todayStartPri'),'date': data.get('date'),'time': data.get('time')}response['is_rising'] = data.get('nowPri') > data.get('todayStartPri')sub = abs(float(data.get('nowPri')) - float(data.get('todayStartPri')))  # 差值response['sub'] = float('%.3f' % sub)return response
"""
stock api
{'resultcode': '200','reason': 'SUCCESSED!','result': [{'data': {'buyFive': '123700','buyFivePri': '33.780','buyFour': '41262','buyFourPri': '33.790','buyOne': '11747','buyOnePri': '33.820','buyThree': '134600','buyThreePri': '33.800','buyTwo': '92600','buyTwoPri': '33.810','competitivePri': '33.820','date': '2020-05-29','gid': 'sh600036','increPer': '-1.17','increase': '-0.400','name': '招商银行','nowPri': '33.820','reservePri': '33.850','sellFive': '13100','sellFivePri': '33.890','sellFour': '95400','sellFourPri': '33.880','sellOne': '1500','sellOnePri': '33.850','sellThree': '1000','sellThreePri': '33.870','sellTwo': '1200','sellTwoPri': '33.860','time': '15:00:00','todayMax': '34.130','todayMin': '33.700','todayStartPri': '33.860','traAmount': '1260905545.000','traNumber': '372374','yestodEndPri': '34.220'},'dapandata': {'dot': '33.820','name': '招商银行','nowPic': '-0.400','rate': '-1.17','traAmount': '126091','traNumber': '372374'},'gopicture': {'minurl': 'http://image.sinajs.cn/newchart/min/n/sh600036.gif','dayurl': 'http://image.sinajs.cn/newchart/daily/n/sh600036.gif','weekurl': 'http://image.sinajs.cn/newchart/weekly/n/sh600036.gif','monthurl': 'http://image.sinajs.cn/newchart/monthly/n/sh600036.gif'}}],'error_code': 0
}

获取小程序应用名字

在app.yml中定义小程序的名字,注册路由返回给小程序前端

published:- app:category: lifeapplication: weathername: 天气publish_date: 2018-10-01url: /service/weatherdesc: this is a weather app.- app:category: lifeapplication: backup-imagename: 图片备份publish_date: 2018-10-02url: /service/imagedesc: this is a backup image app.- app:category: lifeapplication: stockname: 股票publish_date: 2018-10-03url: /service/stockdesc: this is a stock app.- app:category: lifeapplication: constellationname: 星座运势publish_date: 2018-10-03url: /service/constellationdesc: this is a constellation app.- app:category: lifeapplication: jokename: 笑话publish_date: 2018-10-03url: /service/jokedesc: this is a joke app.

apis\views\menu.py

import os
import yamlfrom django.http import JsonResponsefrom backend import settingsimport utils.responsedef init_app_data():data_file = os.path.join(settings.BASE_DIR, 'app.yaml')with open(data_file, 'r', encoding='utf-8') as f:apps = yaml.load(f)return appsdef get_menu(request):global_app_data = init_app_data()published_apps = global_app_data['published']# return JsonResponse(data=published_apps, safe=False, status=200)response = utils.response.wrap_json_response(data=published_apps)return JsonResponse(data=response, safe=False)

总结

backup是定义后端逻辑,如上传图等

server是定义各个app获取接口数据,传递给前端等操作,前端共用一个页面,通过判断应用类型来显示api的数据

小程序中menu是定义app应用页面,如获取后端传递的app名称,跳转app页面等操作

  • 在前段app.json中定义整体的配置

    {"pages": ["pages/index/index","pages/menu/menu","pages/backup/backup","pages/weather/weather","pages/stock/stock","pages/service/service"],"window": {"backgroundTextStyle": "light","navigationBarBackgroundColor": "#fff","navigationBarTitleText": "WeChat","navigationBarTextStyle": "black"},"tabBar": {"list": [{"pagePath": "pages/index/index","text": "首页","iconPath": "","selectedIconPath": ""},{"pagePath": "pages/menu/menu","text": "应用","iconPath": "","selectedIconPath": ""}]},"sitemapLocation": "sitemap.json"
    }
    
// pages/menu/menu.jsconst app = getApp()Page({/*** 页面的初始数据*/data: {grids: [{"name": "应用1"}, {"name": "应用2"}], // 九宫格内容},/*** 生命周期函数--监听页面加载*/onLoad: function(options) {this.updateMenuData()},/*** 请求后台,更新menu数据*/updateMenuData: function() {var that = thiswx.request({url: app.globalData.serverUrl + app.globalData.apiVersion + '/service/menu',success: function(res) {var menuData = res.data.dataconsole.log(menuData)that.setData({grids: menuData})}})},onNavigatorTap: function(e) {var index = e.currentTarget.dataset.indexvar item = this.data.grids[index]console.log(item)if (item.app.application == 'weather') {console.log('-------------')wx.navigateTo({url: '../weather/weather',})} else if (item.app.application == 'backup-image') {wx.navigateTo({url: '../backup/backup',})} else if (item.app.application == 'stock'){wx.navigateTo({url: '../stock/stock',})} else if (item.app.application == 'constellation'){wx.navigateTo({url: '../service/service?type=constellation',})} else if (item.app.application == 'joke'){wx.navigateTo({url: '../service/service?type=joke',})}}
})

Django之开发微信小程序后端-Django篇②相关推荐

  1. Django之开发微信小程序后端-微信小程序篇①

    开始上班~~~ 文章目录 第1章.课程介绍 三类技术要点 小程序技术要点 Django技术要点 服务端技术要点 第2章 小程序开发入门 2-2 小程序开发的准备工作 小程序开发规范 2-3 项目工程的 ...

  2. Django之开发微信小程序后端-会话管理篇③

    文章目录 有状态服务 什么是状态 HTP协议中的状态 有状态服() 4-3 小程序的状态管理 小程序Stronge存储cookies Session中间件 4-4 实现登录功能 用户体系的建立 定义数 ...

  3. 用 Django 开发微信小程序后端实现用户登录

    本文将介绍采用 Django 开发微信小程序后端,通过将用户模块进行重构,并采用JWT来进行用户认证,来解决以下问题: 微信小程序不支持 Cookie,因此不能采用 Django 默认的 Sessio ...

  4. 关于开发微信小程序后端linux使用xampp配置https

    关于开发微信小程序后端linux使用xampp配置https 背景 由于最近开发微信小程序,前后端交互需要使用https协议,故需要配置https服务 服务器环境 服务器系统 ubuntu 环境 xa ...

  5. python微信小程序后端开发_使用django开发微信小程序后端

    tips: 本文面向的对象是已经会使用django开发web后端的人员 微信小程序后端与普通web的区别 微信小程序的后端开发和普通的restful API 大致上相同,只不过要注意以下几点限制 必须 ...

  6. 《微信小程序-证件照换底色》之三:微信小程序接收django的图片并部署到windows服务器上

    实现小程序接收django的图片并部署到windows服务器上 继上一篇:用pycharm搭建django框架接收微信小程序的图片后续 链接: https://blog.csdn.net/qq_449 ...

  7. python开发微信小程序-微信小程序开发:python+sanic 实现小程序登录注册

    开发微信小程序时,接入小程序的授权登录可以快速实现用户注册登录的步骤,是快速建立用户体系的重要一步.这篇文章将介绍 python + sanic + 微信小程序实现用户快速注册登录全栈方案. 微信小程 ...

  8. python开发微信小程序-Python 开发者的微信小程序开发实践

    导读 在知乎上,有人提问"如何使用 Python 开发微信小程序". 其实微信小程序作为一个前端的机制,Python 并不能插上边.只不过可以作为后端接口为微信小程序提供数据服务而 ...

  9. 使用牛刀云开发微信小程序(问题集锦)

    前不久,起步科技正式推出牛刀云1.0,我想这也应该是许多WeX5的忠诚追随者(我也算是其中之一吧)期望的结果了.使用牛刀云开发微信小程序,能够实现使用类似于WeX5的所见即所得组件积木搭建方式构建前端 ...

  10. Mpvue+koa开发微信小程序——腾讯云开发环境的搭建及部署实现真机测试

    为什么写这篇文章? 之前写过一篇文章:微信小程序开发错误:LoginError {type: "ERR_WX_GET_USER_INFO"}解决方法 有的伙伴在这篇文章中评论为什么 ...

最新文章

  1. python多重继承
  2. Codeforces Round #200 (Div. 1)A. Rational Resistance 数学
  3. AndFix解析——(下)
  4. hive安装需要安装mysql区别_HIVE安装系列之一:在Linux中安装mysql,为其作为hive的metastore做准备...
  5. 02、MySQL—数据库基本操作
  6. mysql ibtmp1 太大_mysql5.7 ibtmp1文件过大
  7. 当我设计游戏服务器时,我在想些什么?(1)
  8. ViewDidLoad运行多次的问题
  9. 13.文本文件和二进制文件的区别
  10. 学习 WebService 第三步:一个简单的实例(SoapUI测试REST项目)
  11. android接推流sdk,Android-SDK推流端说明
  12. C语言负数的小数次方,c语言 10 负次方
  13. Scala安装教程(windows和linux)
  14. win7计算器功能详解
  15. docker安装及加速器
  16. linux 写镜像工具下载,镜像写入工具下载
  17. C++基础知识(上)
  18. stm32 开发软件分享
  19. idea激活码?学生如何白嫖使用idea?
  20. 帕斯卡计算机介绍,帕斯卡计算机:第一台被写入百科全书的计算机

热门文章

  1. java中.rtf文件变成文本文件
  2. CDRX6启动失败 提示尝试重新启动计算机和应用程序的解决方法
  3. ctf gif动图分解帧 提取flag
  4. 读书笔记 · AI产品经理的工作流程
  5. TCP、UDP、CoAP、LwM2M、MQTT简单对比
  6. 简单聊聊dorado7,快速入门,内含工具。
  7. 飞鸟尽,良弓藏;狡兔死,走狗烹。
  8. JVM内存管理及垃圾回收机制
  9. 信息安全应急预案整理
  10. Android模拟器加载自定义镜像