只贴下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"}]
}
]
}
5 个评论
要回复文章请先登录或注册
姜智垚
1***@qq.com (作者)
s***@hotmail.com
l***@qq.com
l***@qq.com