微信小程序后端python开发,python做微信小程序后端

大家好,给大家分享一下小程序后端可以用python吗,很多人还不知道这一点。下面详细解释一下。现在让我们来看看!

想法

有时候很久没发朋友圈了突然手痒痒,又不知道发什么好,突然想到自己手头上有个毒鸡汤和励志鸡汤的数据库,大概两万多条,想着无事就把它做成一个小程序,以后想看什么就去里面看看,有励志也有搞笑的。

小程序二维码

在这里插入图片描述

页面

在这里插入图片描述

视频预览

python后端做数据接口实现简单鸡汤文案小程序,开源视频展示使用,有需要源码的小伙伴滴滴我python雨点特效

需求

  1. 展示数据:一个页面展示一个模块
  2. 为了不太单调,加入一个实时钟表样式
  3. 随机播放背景音乐(没有找到好的音乐接口,自己做了一个。)
  4. 两个按钮:一个换文字,一个切换音乐。

接口

  1. 毒鸡汤–post 提交参数:chiose:‘ji’
  2. 好鸡汤–post 提交参数:chiose:‘du’
  3. 英语角–这不是我做的接口,我转接词霸的,因为词霸是http不能放到小程序,所以转接了下。
  4. 背景音乐找不到好用的音乐接口,自己拉歌曲去服务器自己做了一个,目前只有40多首歌,歌名就不说了,你们需要加其它歌曲的跟我说下,我拉进去你们就可以调用了。
  5. 上面接口皆学习使用,请勿恶劣调用,学生不会高超技术,服务器崩了我就再也不分享了。
接口测试

在这里插入图片描述

单页源码

三个页面基本一样,可以在util.js代码复用的,但是ctrl+c,crtl+v速度比较快我就直接复制的,就只发一个页面的了,博客结尾有源码链接,有兴趣的小伙伴自行去取。

index.js
//index.js
//获取应用实例
const app = getApp()
// 获取应用实例
Page({
	data:{
		width:0,
		height:0,
jitang: 'Hello World'
  },
  play_music: function () {
    var music_src=['G.E.M.邓紫棋-句号.mp3','傅如乔-微微.mp3',]
    const bg_music = wx.getBackgroundAudioManager();
    //随机背景音乐
    var a=Math.floor(Math.random() * 42) 
    bg_music.title = music_src[a].replace('.mp3', '');//音乐名
    bg_music.src = 'https://www.cxkboke.top/audio/'+music_src[a]; //音乐地址
  },
 shuaxin: function () {
    this.onLoad()
  },
  copy_text: function (e) {
    var that = this;
    console.log(e);
    wx.setClipboardData({
      data: that.data.OrderModel.OrderNo,
      success: function (res) {
        wx.showToast({
          title: '复制成功',
        });
      }
    });
  },
	//onLoad生命周期函数,监听页面加载
onLoad: function(){
var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading'
    });
    wx.request({
      url: app.globalData.url + 'getJitang',
      method: 'POST',
      data: {
        chiose: 'du'
      },
      success: function (res) {
        console.log(res.data)
        that.setData({
          jitang: res.data.info
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    }),
		//将全局变量Index保存在that中,里面函数调用
		
		//获取系统信息
		wx.getSystemInfo({
			//获取系统信息成功,将系统窗口的宽高赋给页面的宽高
			success: function(res) {
				that.width = res.windowWidth
				that.height = res.windowHeight
			}
		})
	},
	//onReady生命周期函数,监听页面初次渲染完成
	onReady: function(){
		//调用canvasApp函数
		this.canvasClock()
		//对canvasAPP函数循环调用
		this.interval = setInterval(this.canvasClock,1000)
	},
	canvasClock: function(){
		var context = wx.createContext()//创建并返回绘图上下文(获取画笔)
		//设置宽高
		var width = this.width
		var height = this.height
		var R = width/2-55;//设置文字距离时钟中心点距离
		//重置画布函数
		function reSet(){
			context.height = context.height;//每次清除画布,然后变化后的时间补上
            context.translate(width/2, height/2);//设置坐标轴原点
            context.save();//保存中点坐标1
		}
		//绘制中心圆和外面大圆
		function circle(){
			//外面大圆
			context.setLineWidth(2);
            context.beginPath();
            context.arc(0, 0, width/2-30, 0, 2 * Math.PI,true);
            context.closePath();
            context.stroke();
            //中心圆
            context.beginPath();
            context.arc(0, 0, 8, 0, 2 * Math.PI, true);
            context.closePath();
            context.stroke();
		}
		//绘制字体
		function num(){
			// var R = width/2-60;//设置文字距离时钟中心点距离
			context.setFontSize(20)//设置字体样式
            context.textBaseline = "middle";//字体上下居中,绘制时间
            for(var i = 1; i < 13; i++) {
                //利用三角函数计算字体坐标表达式
                var x = R * Math.cos(i * Math.PI / 6 - Math.PI / 2);
                var y = R * Math.sin(i * Math.PI / 6 - Math.PI / 2);
                if(i==11||i==12){//调整数字11和12的位置
                    context.fillText(i, x-12, y+9);
                }else {
                    context.fillText(i, x-6, y+9);
                }
            }
		}
		//绘制小格
		function smallGrid(){
				context.setLineWidth(1);
                context.rotate(-Math.PI/2);//时间从3点开始,倒转90度
                for(var i = 0; i < 60; i++) {
                    context.beginPath();
                    context.rotate(Math.PI / 30);
                    context.moveTo(width/2-30, 0);
                    context.lineTo(width/2-40, 0);
                    context.stroke();
                }
         }
         //绘制大格
         function bigGrid(){
         	context.setLineWidth(5);
            for(var i = 0; i < 12; i++) {
                context.beginPath();
                context.rotate(Math.PI / 6);
                context.moveTo(width/2-30, 0);
                context.lineTo(width/2-45, 0);
                context.stroke();
            }
         }
         //指针运动函数
        function move(){
            var t = new Date();//获取当前时间
            var h = t.getHours();//获取小时
            h = h>12?(h-12):h;//将24小时制转化为12小时制
            var m = t.getMinutes();//获取分针
            var s = t.getSeconds();//获取秒针
            context.save();//再次保存2
            context.setLineWidth(7);
            //旋转角度=30度*(h+m/60+s/3600)
            //分针旋转角度=6度*(m+s/60)
            //秒针旋转角度=6度*s
            context.beginPath();
            //绘制时针
            context.rotate((Math.PI/6)*(h+m/60+s/3600));
            context.moveTo(-20,0);
            context.lineTo(width/4.5-20,0);
            context.stroke();
            context.restore();//恢复到2,(最初未旋转状态)避免旋转叠加
            context.save();//3
            //画分针
            context.setLineWidth(5);
            context.beginPath();
            context.rotate((Math.PI/30)*(m+s/60));
            context.moveTo(-20,0);
            context.lineTo(width/3.5-20,0);
            context.stroke();
            context.restore();//恢复到3,(最初未旋转状态)避免旋转叠加
            context.save();
            //绘制秒针
            context.setLineWidth(2);
            context.beginPath();
            context.rotate((Math.PI/30)*s);
            context.moveTo(-20,0);
            context.lineTo(width/3-20,0);
            context.stroke();
        }
		function drawClock(){
			reSet();
			circle();
			num();
			smallGrid();
			bigGrid();
			move();
		}
		drawClock()//调用运动函数
		// 调用 wx.drawCanvas,通过 canvasId 指定在哪张画布上绘制,通过 actions 指定绘制行为
		wx.drawCanvas({
			canvasId:'myCanvas',
			actions: context.getActions()
		})
	},
	//页面卸载,清除画布绘制计时器
	onUnload:function(){
		clearInterval(this.interval)
	}
})
index.wxml
<canvas canvas-id="myCanvas" class="canvas"></canvas>
<view class="view_box">
<text class='txt' selectable="true" bindlongtap="copy_text">{{jitang}}</text>
<button class='Scancode1' bindtap="shuaxin">再来一碗</button>
<button class='Scancode2' bindtap="play_music">随机一曲</button>
</view>
index.wxss
.view_box{
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}
.canvas{
	width: 100%;
	height: 100%;
	position: fixed;
}
.Scancode1 {
  font-size: 39rpx;
  background: #fff;
  position: fixed;
  bottom: 0;
  display: flex;
  width: 100%;
  justify-content: center;
  /* font-family: FangSong; */
  margin-bottom: 20rpx;
}
.Scancode2 {
  font-size: 39rpx;
  background: #fff;
  position: fixed;
  bottom: 0;
  display: flex;
  width: 100%;
  justify-content: center;
  /* font-family: FangSong; */
  margin-bottom: 140rpx;
}
.txt{
  font-size: 39rpx;
  margin-top: 80rpx;
  /* font-family: FangSong; */
  display: block;
}

项目源码链接

点此

后端源码

utils.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/04/29 16:50
# @Author  : Cxk
import json,os,time
import datetime, random
# 导入模块
import requests
import jsonpath
from urllib.request import urlretrieve

import json,random,requests
from pyncm import apis

def getMp3File(url,name):
    try:
        res = requests.get(url)
        music = res.content
        filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'music')
        allFileName = os.path.join(filepath, name+".mp3")
        with open(allFileName, 'ab') as file: #保存到本地的文件名
            file.write(res.content)
            file.flush()
    except Exception as e:
        write_error(e)
        
def randomDownMusic():
    try:
        # 获取歌曲信息
        allPlaylistsId = []
        for i in apis.playlist.GetTopPlaylists()['list']:
            allPlaylistsId.append(i['id'])
        music_info = apis.playlist.GetPlaylistInfo(random.choice(allPlaylistsId), offset=0, total=True, limit=1000)['playlist']['tracks']
        allMusicId = []
        for i in music_info:
            allMusicId.append(str(i['id'])+"-"+i['ar'][0]['name']+"-"+i['name'])
        chioseMusic = random.choice(allMusicId)
        getMp3File(apis.track.GetTrackAudio(chioseMusic.split('-')[0])['data'][0]['url'],chioseMusic.split('-')[1]+"-"+chioseMusic.split('-')[2].replace('"','').replace("'", ''))
    except Exception as e:
        write_error(e)
        
def get_music_name(name,types,page):
    data=[]
    cout=1
    try:
        param = {
        "input":name,
        "filter":"name",
        "type":types,
        "page": str(page),
        }
        url = 'https://music.liuzhijin.cn/'
        headers = {
        "user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36",
        # 判断请求是异步还是同步
        "x-requested-with":"XMLHttpRequest",
        }
        # 模拟网页请求
        res = requests.post(url=url,data=param,headers=headers)
        # 解析网页返回数据
        json_text = res.json()
        # 提取数据
        title = jsonpath.jsonpath(json_text,'$..title')
        author = jsonpath.jsonpath(json_text,'$..author')
        url = jsonpath.jsonpath(json_text, '$..url')
        #   print(title,author,url)
        # 数据拼接
        for i in range(len(title)):
            temp={}
            temp['id']=str(cout)
            temp['musicName']=title[i]
            temp['author']=author[i]
            temp["address"]=url[i]
            cout+=1
            data.append(temp)
        return data
    except Exception as e:
        write_error(e)
        
def paging(page, limit, dictArray):
    start = (page - 1) * limit
    end = page * limit if len(dictArray) > page * limit else len(dictArray)
    ret = [dictArray[i] for i in range(start, end)]
    all_page = int(len(dictArray)/limit)+1
    return ret, all_page

def response_return(code, msg, data):
    """[summary]
    Args:
        code ([type]): 200(请求成功),404(请求失败),500(服务器出错)
        msg ([type]): msg
        data ([type]): json_data
    Returns:
        [type]: [deion]
    """
    if data == None:
        data = []
    return json.dumps({'code': code, 'msg': msg, 'data': list(data)}, ensure_ascii=False)

def write_error(e):
    """[summary]
    Args:
        e ([type]): [deion]
    """
    folder_path='./error_log/'
    if not os.path.exists(folder_path):  #判断是否存在文件夹如果不存在则创建为文件夹
        os.makedirs(folder_path)
    error_time=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
    (filepath,error_file) = os.path.split(e.__traceback__.tb_frame.f_globals['__file__'])
    error_line=e.__traceback__.tb_lineno
    with open(folder_path+'error.txt', 'a+',encoding='UTF-8') as file_handle:
        file_handle.write("time: %s\nfile: %s -- line: %s -- error: %s" %(error_time,error_file,error_line, str(e)))  # 写入
        file_handle.write('\n\n')
        
def GetNameByEveryDir(file_dir):  
    # Input   Root Dir and get all img in per Dir.
    # Out     Every img with its filename and its dir and its path  
    FileNameWithPath = [] 
    FileName         = []
    FileDir          = []
    for root, dirs, files in os.walk(file_dir):  
        for file in files:  
            FileNameWithPath.append(os.path.join(root, file))  # 保存图片路径
            FileName.append(file)                              # 保存图片名称
            FileDir.append(root[len(file_dir):])               # 保存图片所在文件夹
    return FileName,FileNameWithPath,FileDir
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/12/17 20:02
# @Author  : Cxk
from utils import *
from flask import Flask, render_template, Blueprint, request, send_file,redirect,flash, url_for, session
import requests
from datetime import datetime, date, timedelta
from poem_data import *
import threading

hot_soup = Blueprint('hot_soup', __name__)

def startGetMusicFileThread():
    t = threading.Thread(target=randomDownMusic)
    t.start()

@hot_soup.route('/getJitang', methods=['GET', 'POST'])
def getJitang():
    try:
        if request.method == 'POST':
            startGetMusicFileThread()
            if not request.data:
                # 检测是否有数据
                return json.dumps({'msg': "错误,没有请求参数!", 'info': [{'poemName': '无', 'author': '无', 'poem': '无'}]},ensure_ascii=False)
            post_data = request.data.decode('utf-8')
            # 获取到POST过来的数据,因为我这里传过来的数据需要转换一下编码。根据具体情况而定
            data_json = json.loads(post_data)
            chiose = data_json['chiose']
            if chiose=='ji':
                print(jitang_select()[0][1])
                return json.dumps({'code':'200' , 'info': jitang_select()[0][1]}, ensure_ascii=False)
            elif chiose == 'du':
                print(dutang_select()[0][1])
                return json.dumps({'code': '200', 'info': dutang_select()[0][1]}, ensure_ascii=False)
        else:
            return json.dumps({'msg': "请求失败,请用post提交", 'info': 'None'},
                              ensure_ascii=False)
    except Exception as e:
        write_error(e)
        
@hot_soup.route('/getMusic', methods=['GET', 'POST'])
def getMusic():
    try:
        filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'music')
        info = os.listdir(filepath)
        print(info)
        return json.dumps({'msg': "请求成功", 'info':info},ensure_ascii=False)
    except Exception as e:
        write_error(e)
        
@hot_soup.route('/music/<file_names>', methods=['GET'])
def music(file_names):
    """
    机器合成音频传输播放
    @@@
    #### args

    | args | nullable | type | remark |
    |--------|--------|--------|--------|
    |    file_names    |    false    |    string   |    音频文件名    |
    
    #### return
    - ##### file
    > 文件输出
    @@@
    """
    try:
        filepath = os.path.join(os.path.dirname(
            os.path.abspath(__file__)), 'music')
        filename = file_names
        file = os.path.join(filepath, filename)
        return send_file(file)
    except Exception as e:
        write_error(e)
        return response_return('500', 'Unknown server error', None)

@hot_soup.route('/getYingyu', methods=['GET', 'POST'])
def getYingyu():
    try:
        if request.method == 'POST':
            startGetMusicFileThread()
            m = random.randint(1, 730)
            chioseDay = (date.today() + timedelta(days = -m)).strftime("%Y-%m-%d")    # 昨天日期
            url = 'http://sentence.iciba.com/index.php?c=dailysentence&m=getdetail&title='+chioseDay
            r = requests.post(url)
            a = r.json()
            try:
                return json.dumps({'msg': '200', 'info': a['content'] + '\n' + a['note']}, ensure_ascii=False)
            except:
                return json.dumps({'msg': '200', 'info': '这碗洒了,再来一碗!'}, ensure_ascii=False)
        else:
            return json.dumps({'msg': "请求失败,请用post提交", 'info': '这碗洒了,再来一碗!'},ensure_ascii=False)
    except Exception as e:
        write_error(e)

数据库

#-----------------------------------------------------------------------鸡汤/毒汤文-------------------------------------------------------
def jitang_opendb():
    conn = sqlite3.connect("jitang_date.db")
    cur = conn.execute(
        """create table if not exists jitang_info(id integer PRIMARY KEY autoincrement,jitang varchar(256))""")
    return cur, conn


#  往数据库中添加内容
def jitang_insertData(jitang):
    hel = jitang_opendb()
    hel[1].execute("insert into jitang_info(jitang) values ('%s')" % (jitang))
    hel[1].commit()
    hel[1].close()


# 根据诗名查找诗整体信息
def jitang_select():
    hel = jitang_opendb()
    cur = hel[1].cursor()
    cur.execute("SELECT * FROM jitang_info ORDER BY RANDOM() limit 1")
    res = cur.fetchall()
    return res
    cur.close()

#根据诗句模糊查找诗整体信息
def jitang_selectParagraphss(strs):
    hel = jitang_opendb()
    cur = hel[1].cursor()
    cur.execute("select * from jitang_info where jitang like '%%%s%%'"%strs)
    res = cur.fetchall()
    return res
    cur.close()


def dutang_opendb():
    conn = sqlite3.connect("jitang_date.db")
    cur = conn.execute(
        """create table if not exists dutang_info(id integer PRIMARY KEY autoincrement,dutang varchar(256))""")
    return cur, conn


#  往数据库中添加内容
def dutang_insertData(dutang):
    hel = dutang_opendb()
    hel[1].execute("insert into dutang_info(dutang) values ('%s')" % (dutang))
    hel[1].commit()
    hel[1].close()


# 根据诗名查找诗整体信息
def dutang_select():
    hel = dutang_opendb()
    cur = hel[1].cursor()
    cur.execute("SELECT * FROM dutang_info ORDER BY RANDOM() limit 1")
    res = cur.fetchall()
    return res
    cur.close()
    
#根据诗句模糊查找诗整体信息
def dutang_selectParagraphss(strs):
    hel = dutang_opendb()
    cur = hel[1].cursor()
    cur.execute("select * from dutang_info where dutang like '%%%s%%'"%strs)
    res = cur.fetchall()
    return res
    cur.close()

鸡汤数据库

鸡汤数据库

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值