python 操作微信云数据库

class DB():
    def __init__(self):
        self.WECHAT_URL = 'https://api.weixin.qq.com/'
        self.APP_ID = 'wxc8e638b461ec4859'
        self.APP_SECRET = '5bcd735f03e86317a4811f4e3dab3134'
        self.ENV = 'game-mtzwk'  # 云环境ID


    def get_access_token(self):
        '''
        获取小程序token
        '''
        url='{0}cgi-bin/token?grant_type=client_credential&appid={1}&secret={2}'.format(self.WECHAT_URL,self.APP_ID,self.APP_SECRET)
        response =requests.get(url)
        result=response.json()
        print(result)
        return result['access_token']


    def add_data(self,collectionName,accessToken):
        '''
        新增数据
        '''
        url='{0}tcb/databaseadd?access_token={1}'.format(self.WECHAT_URL,accessToken)
        query="db.collection('%s').add({data:{_id:'112',key:1,value:'2',kj:2}})"%collectionName
        print(query)
        data={
     
            "env":self.ENV,  # 云环境ID
            "query":query
        }
        response  = requests.post(url,data=json.dumps(data))
        print('2.新增数据:'+response.text)


    def databaseUpdate(self,accessToken,collectionName):
        """"
        .where() 该集合所在记录的检索
        这个例子是将集合里age=14所有记录自增1
        """
        url = '{0}tcb/databaseupdate?access_token={1}'.format(self.WECHAT_URL, accessToken)
        data = {
     
            "env": self.ENV,
            # "query": "db.collection('%s').where({_id:'111'}).update({data:{value: 222}})"%collection_name
            "query": "db.collection('%s').doc('111').set({data:{value: 2212}})"%collectionName
        }
        print(data)
        response = requests.post(url, data=json.dumps(data))
        result = response.json()
        print(result)     #将返回值打印


    # 查询某个集合中的数据,代码如下:
    def query_data(self,accessToken,collection_name):
        '''
        查询数据
        '''
        url='{0}tcb/databasequery?access_token={1}'.format(self.WECHAT_URL,accessToken)
        query="db.collection('%s').limit(100).get()"%collection_name
        data={
     
            "env":self.ENV,
            "query":query
        }
        response  = requests.post(url,data=json.dumps(data))
        print('3.查询数据:'+response.text)
        result=response.json()
        print(result)
        # resultValue =json.loads(result)
        # return resultValue['_id']


    def db(self,):
        accessToken = self.get_access_token()
        print('accessToken:', accessToken)
        collectionName = 'test'
        # add_data(collectionName, accessToken)
        # query_data(accessToken, collectionName)
        self.databaseUpdate(accessToken, collectionName)

你可能感兴趣的:(Python,python)