Python operates the small program cloud development database to add, delete, modify and check


Recently, I want to synchronize some data in the local database to the cloud database of the applet. Since the server is python, it is more convenient to write to the cloud database of the applet after reading synchronously through python.
See the cloud development of the applet to provide a series of HTTP api related documents , and the addition, deletion, modification and query of the cloud development database will be realized soon. Roughly divided into the following two steps.

1. Get access_token

The two necessary parameters for calling the cloud database are the appid and appsecret of the applet. These two values ​​can be obtained by logging into the background of your own applet. The access_token is valid for two hours, and if it times out, it will be requested again, so here I created a json file to save the latest token and update time.
insert image description here

def get_access_token():
    """"
    获取access_token
    """
    with open("token.json", "r") as f:
        config = json.loads(f.read())
    now_time = int(time.time())
    # access_token两小时有效,超时则重新请求获取
    if now_time - config.get("update_time", 0) >= 7200:
        appid = '******'  # 小程序ID
        appsecret = '******'  # 小程序秘钥
		wechart_url = f'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={
      
      appid}&secret={
      
      appsecret}'
        response = requests.get(wechart_url)
        result = response.json()
        config = {
    
    
            "token": result["access_token"],
            "update_time": now_time
        }
        with open("token.json", "w") as f:
            f.write(json.dumps(config))

    return config["token"]  # 将返回值解析获取access_token

2. Perform database operations through the database api

After obtaining the access_token, you can perform a series of operations of adding, deleting, and changing database collections and records.
The query required for each record query is the environment id env and query query statement of the applet. Additions, deletions, modifications, and queries correspond to different urls, all of which are post requests. Just construct parameter query.

class Cloud:
    def __init__(self, env, collection_name):
        self.access_token = get_access_token()
        self.query_url = 'https://api.weixin.qq.com/tcb/databasequery?access_token={}'.format(self.access_token)
        self.add_url = 'https://api.weixin.qq.com/tcb/databaseadd?access_token={}'.format(self.access_token)
        self.update_url = 'https://api.weixin.qq.com/tcb/databaseupdate?access_token={}'.format(self.access_token)
        self.delete_url = 'https://api.weixin.qq.com/tcb/databasedelete?access_token={}'.format(self.access_token)
        self.env = env
        self.collection_name = collection_name
        self.post_data = {
    
    "env": self.env}  # 请求参数,每次的请求参数需要env环境id和query查询语句

    def query(self, search_param):
        """
        search_param: dict
        """
        self.post_data["query"] = f"db.collection('{
      
      self.collection_name}').where({
      
      search_param}).get()"
        res = requests.post(self.query_url, data=json.dumps(self.post_data))
        return res.json()

    def update(self, search_param, update_dict):
        """
        search_param:dict 查询要更新的某条记录
        update_dict:dict 要修改的值
        """
        update_data = "{data:%s}" % update_dict
        self.post_data["query"] = f"db.collection('{
      
      self.collection_name}').where({
      
      search_param}).update({
      
      update_data})"
        response = requests.post(self.update_url, data=json.dumps(self.post_data))
        result = response.json()
        return result

    def add(self, new_data):
        """
        new_data: list of dict
        """
        new_data = "{data:%s}" % new_data
        self.post_data["query"] = f"db.collection('{
      
      self.collection_name}').add({
      
      new_data})"
        response = requests.post(self.add_url, data=json.dumps(self.post_data))
        result = response.json()
        # 执行成功返回状态码0
        if result["errcode"] == 0:
            return result['id_list']

    def delete(self, search_param):
        self.post_data["query"] = f"db.collection('{
      
      self.collection_name}').where({
      
      search_param}).remove()"
        res = requests.post(self.delete_url, data=json.dumps(self.post_data))
        return res.json()

3. Running results

Then write the main function to test the addition, deletion, modification and query

if __name__ == '__main__':
    _env = "*****"# 自己的云开发环境id
    _collection_name = "projects"# 需要查询的数据集合名称
    # 新增
    Cloud(_env, _collection_name).add([{
    
    
        "name": "test",
        "price": 0,
        "language": "python"
    }])
    # 修改
    print(Cloud(_env, _collection_name).update({
    
    "name": "test"}, {
    
    "name": "update_test"}))
    # 修改后查询
    print(Cloud(_env, _collection_name).query({
    
    "name": "update_test"}))
    # 删除
    print(Cloud(_env, _collection_name).delete({
    
    "name": "update_test"}))
    # 删除后查询
    print(Cloud(_env, _collection_name).query({
    
    }))

The running results are as follows, and the overall process is completed.
insert image description here

The display effect of the final interface data can be viewed through the applet

insert image description here

Guess you like

Origin blog.csdn.net/Demonslzh/article/details/125723297