前言
最近自己正好有时间,想要自己搭建微信小程序,也正好记录一下自己的搭建过程和内容。
搭建准备工作
这里我使用的时pycharm编辑器。在后端开发中,我们需要三个库:
import pymysql
from flask import request, Flask, jsonify
from flask_cors import CORS
连接数据库方法
# 连接数据库
# db = pymysql.connect(host='连接数据库的ip地址',port='端口', user='用户名', password='密码', db='连接的数据库')
db = pymysql.connect(host='127.0.0.1', user='root', password='123456', db='sql_tp')
print(db.port)
cursor = db.cursor() # 指定数据库指针
启动后端方法
# 启动后端
app = Flask(__name__)
CORS(app, resources=r'/*') # 解决跨域问题
post和get请求方法
请求的方法基本就是这样,通过组合能实现不同的请求,不拘泥于形式。
# ------------------------------------------------------------------------------------
# ---------------------------------------测试使用方法-----------------------------------
# 接受post请求,收到值返回说明
@app.route('/url', methods=['POST'])
# 后端接口的入口,使用POST方法 比如进入在boot下的word表,可以设“/boot/word”
def func(): # 接口触发做的事情if request.method == "POST": # 判断是不是post请求username = request.form.get("username") # 接受前端的参数# t = [t1,t2,t3,t4,t5,t6,t7,t8,t9,t10]t = [1,2,3,1,2,3,1,2,3,1] # 假设接受了多个数据放到t列表中vales = ""for n,i in enumerate(t): # 将vales变成字符串,就是将t中的数据连接做成sql。if n != len(t)-1:vales = vales+str(i)+","else:vales = vales + str(i)try:sql = "insert into wjy_xcx_tmp value ("+vales+");" # 插入sql语句。cursor.execute(sql) # 在后端执行的sql语句cursor.execute("commit;") # 在后端执行的sql语句cursor.execute("select count(*) from wjy_xcx_tmp;") # 在后端执行的sql语句date = cursor.fetchone() # 获取所有查询到的记录,fechaone()返回一条print(date)return jsonify(date) # 返回sql查询出的数据。except Exception as e:return "-1"# return jsonify([]) 返回json数组
# ------------------------------------------------------------------------------------
# ------------------------------------------------------------------------------------# login登录操作,返回数据库查询到的密码并返回(已完成返回密码操作)
@app.route('/my_system/login', methods=["POST"]) # 使用POST请求
def login():if request.method == 'POST':phone = request.form.get("phone")# 做异常测试try:# 发送数据库cursor.execute("select 密码 from tp_ghao20221230 where 手机号=" + str(phone))data_login = cursor.fetchone() # 返回第一条查询信息if data_login != None:return jsonify(data_login) # 号码查找到密码,返回密码else:return '1' # 数据库未查询到,返回1except Exception as e:print("failed:", e)return '-1' # 登录操作异常,返回-1# 修改密码操作(已完成修改密码操作)
@app.route('/my_system/login/update', methods=["POST"]) # 使用POST请求
def login_update():if request.method == 'POST':phone = request.form.get("phone")login_password = request.form.get("login_password")# 做异常测试try:# 发送数据库cursor.execute("update tp_ghao20221230 set 密码=\"" + str(login_password) + "\" where 手机号=" + str(phone))db.commit()return '1' # 完成修改密码操作,返回1except Exception as e:print("failed:", e)return '-1' # 未完成修改操作,返回-1
主函数
if __name__ == '__main__':app.run(host='0.0.0.0', port=自己定义的接口) # 启动后端服务器,定义接口,监听端口;0.0.0.0表示都可以访问的地址。db.close()
总结
全部代码可以直接将所有代码放在一起就是一个python的后端程序了。实现起来还是比较简单的。大家可以通过修改sql和部分代码实现自己的python后端。