1***@qq.com
1***@qq.com
  • 发布:2022-08-03 20:30
  • 更新:2023-12-26 10:00
  • 阅读:1035

python后端直接通过http的方式操作数据库, 不通过web控制台或者云函数

分类:uniCloud

只贴下python的insert数据库的操作, 其他语言类似
免费版的url = 'https://api.bspapp.com/client'
收费版的是url = 'https://api.next.bspapp.com/client'自己替换下

import requests  
import json  
import time  
import hmac  
import hashlib  

def insert():  
    # accessToken是后面header需要的参数  
    accessToken = get_access_token()  
    url = 'https://api.bspapp.com/client'  
    payload = {  
        'method': 'serverless.function.runtime.invoke',  
        'params': json.dumps(  
            {  
                "functionTarget": "DCloud-clientDB",  
                "functionArgs": {  
                    "command": {  
                        "$db": [  
                            {  
                                "$method": "collection",  
                                "$param": ["表名"]  
                            }, {  
                                "$method": "add",                        #如果是update这里add就换成update. 写法类似于mongodb的  
                                "$param": [{"字段名1": "字段值1"}]  
                            }  
                        ]  
                    }  
                }  
            }  
        ),  
        # spaceId自己在web控制台找, timestamp是时间戳  
        'spaceId': spaceId,  
        'timestamp': int(round(time.time() * 1000)),  
        'token': accessToken,  
    }  
    headers = {  
        'content-type': 'application/json',  
        'x-basement-token': accessToken,  
        'x-serverless-sign': get_sign(payload),  
    }  
    payload = json.dumps(payload)  
    # 发送post请求  
    response = requests.post(url, data=payload, headers=headers)  
    result = json.loads(response.text)  
    return result  

#获取access_token的方法, access_token一段时间会过期  
def get_access_token():  
     url = 'https://api.bspapp.com/client'  
     payload = {  
           'method': 'serverless.auth.user.anonymousAuthorize',  
            'params': '{}',  
            'spaceId': spaceId,  
            'timestamp': int(round(time.time() * 1000)),  
      }  
      headers = {  
             'Content-Type': 'application/json',  
              'x-serverless-sign': get_sign(payload)  
      }  

      payload = json.dumps(payload)  
      response = requests.post(url, data=payload, headers=headers)  
      result = json.loads(response.text)  

      access_token = result['data']['accessToken']  
      return access_token   

# 签名参数  
def get_sign(param):  
    #按照键名的升序排序  
    param = ksort(param)  
    #键与值 等号拼接的数组, 结果如["键1=值1", "键2=值2", "键3=值3"...]  
    signList = []  
    for k, v in param:  
        if v != '':  
            signList.append(k + '=' + str(v))  
    # 每个参数对拼接&并连在一起的字符串, 结果如 "键1=值1&键2=值2&键3=值3"...  
    signPars = '&'.join(signList)  
    #md5 hmac加密, clientSecret自己的web控制台里找, hmac, hashlib是python自带的库..其他语言也应该有类似的  
    sign = hmac.new(clientSecret.encode('utf-8'), signPars.encode('utf-8'), digestmod=hashlib.md5).hexdigest()  
    return sign  

#按照键名的升序排序, php里直接有ksort() 可以使用  
def ksort(d):  
    return [(k, d[k]) for k in sorted(d.keys())]  

下面是一些写法举例  
查询,比如查_id: 17的那条数据  
"command": {  
                        "$db": [  
                            {  
                                "$method": "collection",  
                                "$param": ["表名"]  
                            }, {  
                                "$method": "where",  
                                "$param": [{"_id": 17}]  
                            }, {  
                                "$method": "get",  
                                "$param": []  
                            }  
                        ]  
                    }  

删除, 比如删除_id: 17的那条数据  
"command": {  
                        "$db": [  
                            {  
                                "$method": "collection",  
                                "$param": ["表名"]  
                            }, {  
                                "$method": "where",  
                                "$param": [{"_id": 17}]  
                            }, {  
                                "$method": "remove",  
                                "$param": []  
                            }  
                        ]  
                    },  

改, 修改_id:17的那条数据  
"command": {  
                        "$db": [  
                            {  
                                "$method": "collection",  
                                "$param": ["表名"]  
                            }, {  
                                "$method": "where",  
                                "$param": [{"_id": 17]  
                            }, {  
                                "$method": "update",  
                                "$param": [{"字段1":"字段值1"}]  
                            }  
                        ]  
                    }
2 关注 分享
3***@qq.com 工程狮

要回复文章请先登录注册

姜智垚

姜智垚

请问使用inc 自增怎么没有反应
2023-12-26 10:00
1***@qq.com

1***@qq.com (作者)

回复 s***@hotmail.com :
我一直在用, 没有问题
2023-01-22 16:26
s***@hotmail.com

s***@hotmail.com

还有没有伙伴用这种方式的,现在这种方式还行么,获取token都一直提示SignatureNotMatch,区别是我用C#做后端的
python代码也测试了,也一样的错误
2022-12-28 17:54
l***@qq.com

l***@qq.com

回复 l***@qq.com :
自己找到原因了,数据表里没有开放权限。现在可以正常使用,非常感谢大佬提供的代码!
2022-10-09 20:53
l***@qq.com

l***@qq.com

大佬,我用这个代码返回的是:TOKEN_INVALID_ANONYMOUS_USER
spaceid和clientSecret都是对的,是现在不能用这个了吗?
2022-10-09 20:40