本文将接前文,继续讲述python程序对微信云开发数据库的操作。

间接操作

间接操作指的是python通过云函数对云开发数据库进行操作。所有的操作都是在获取access_token的前提下进行的,不懂的同学可以参考:链接: link.
同时由于请求python请求云函数的代码基本类似,只有在data里面进行参数的变换即可,给出一个例子:

1
2
3
4
5
6
7
8
9
10
11
def xxxx(self):
//在函数括号内需要添加参数
ACCESS_TOKEN = xxx //获取的access_token
ENV = xxx //用户的数据库环境ID
FUNCTION_NAME = xxx //所要执行的云函数名
url = 'https://api.weixin.qq.com/tcb/invokecloudfunction?access_token=' + ACCESS_TOKEN + '&env=' + ENV + '&name=' + FUNCTION_NAME
data = {
//所要传输的参数
}
response = requests.post(url=url, data=json.dumps(data))
result = response.json()

创建集合

云函数:

1
2
3
4
5
6
7
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
exports.main = async (event, context) => {
return await db.createCollection(event.id)
//event.id是python传输的数据,为该集合的名字
}

python:

1
2
3
4
5
6
7
def createCollection(self,id):
....
....
data = {
'id':id,
}
....

查询记录

云函数:

1
2
3
4
5
6
7
8
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
exports.main = async (event, context) => {
return await db.collection(event.id).get();
//event.id是python传输的数据,为该集合的名字
//.get()调用云函数方法,获取该集合下的所有数据,可以加上.where()筛选,后续更新、新增等操作类似
}

python:

1
2
3
4
5
6
7
def databaseQuery(self,id):
....
....
data = {
'id':id,
}
....

插入记录

云函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
exports.main = async (event, context) => {
return await db.collection(event.id).add({
data: {
description: event.description,
due: event.due
}
});
//event.id是python传输的数据,为该集合的名字
//.add()新增记录函数
}

python:

1
2
3
4
5
6
7
8
9
10
11
12

def databaseQuery(self,id):
....
....
description=xxxx
due=xxxx
data = {
'id':id,
'description': description,
'due': due
}
....

删除记录

云函数:

1
2
3
4
5
6
7
8
9
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
exports.main = async (event, context) => {
return await db.collection(event.id).remove();
//event.id是python传输的数据,为该集合的名字
//.remove()删除记录函数
//可用.doc().where()等定位具体某种信息
}

python:

1
2
3
4
5
6
7
8
9
def databaseQuery(self,id):
....
....
description=xxxx
due=xxxx
data = {
'id':id,
}
....

更新记录

云函数:

1
2
3
4
5
6
7
8
9
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
exports.main = async (event, context) => {
return await db.collection(event.id).update();
//event.id是python传输的数据,为该集合的名字
//.update()更新记录函数
//可用.doc().where()等定位具体某种信息
}

python:

1
2
3
4
5
6
7
8
9
def databaseQuery(self,id):
....
....
description=xxxx
due=xxxx
data = {
'id':id,
}
....

总结

隔了好久终于把第二部分写了,也很感谢第一部分有些网友指出的错误,已经修改,这篇一样,希望得到大家的交流指点。

也欢迎来我的[个人博客](ZLF - 钟林锋的博客 (zlfeng.cn))交流