farmbot开发入门教程-授权
说明:
介绍使用 Python 获取授权请求的令牌
存储你的授权令牌。安全地存储您的授权令牌。它授予对您的 FarmBot 和 FarmBot Web App 帐户的完全访问和控制权
所需库。以下示例需要 FarmBot Python 库或Requests库。要安装,请python -m pip install farmbot requests在命令行中运行。您的系统可能要求您使用python3而不是python。强烈建议使用虚拟环境。如果您看到以 结尾的错误callback_api_version,请运行python -m pip install --upgrade paho-mqtt==1.6.1。
运行 Python 代码。您可以通过将 Python 代码粘贴到新文件中来执行它,例如run.py可以通过python run.py命令行执行该文件。
通过 FarmBot Python 库
import json
from getpass import getpass
from farmbot import FarmbotToken
# inputs
SERVER = input('FarmBot Web App account server (press <Enter> for https://my.farm.bot): ') or 'https://my.farm.bot'
EMAIL = input('FarmBot Web App account login email: ')
PASSWORD = getpass('FarmBot Web App account login password: ')
# get your FarmBot authorization token
token_string = FarmbotToken.download_token(EMAIL, PASSWORD, SERVER)
TOKEN = json.loads(token_string)
print(f'{TOKEN = }')
通过Python
import json
from getpass import getpass
import requests
# inputs
SERVER = input('FarmBot Web App account server (press <Enter> for https://my.farm.bot): ') or 'https://my.farm.bot'
EMAIL = input('FarmBot Web App account login email: ')
PASSWORD = getpass('FarmBot Web App account login password: ')
# get your FarmBot authorization token
headers = {'content-type': 'application/json'}
user = {'user': {'email': EMAIL, 'password': PASSWORD}}
response = requests.post(f'{SERVER}/api/tokens',
headers=headers, json=user)
TOKEN = response.json()
print(f'{TOKEN = }')
复制和粘贴
- 当示例中出现以下行时,将其替换:
# TOKEN = ...
- 粘贴上面运行获取令牌示例代码时粘贴的令牌数据。例如:
TOKEN = {"token": {"unencoded":{"aud":"unknown","sub":123,"iat":1234567890,"jti":"b52b68fb-5cc2-a9be-7aaf-ecc8837a2fa9","iss":"//my.farm.bot:443","exp":1234567890,"mqtt":"abc-def.rmq.cloudamqp.com","bot":"device_456","vhost":"xqigvtsn","mqtt_ws":"wss://abc-def.rmq.cloudamqp.com:443/ws/mqtt"},"encoded":"rFr6edHr11GDLITjaanofZxC4dM6TCC9UuHG.Kzx87wRkKvejWWjuigwX0i3hO8hi97pJ70m1bD2I5JRuksjE6E3gRIOVwoF5f8X4UCtftuVCsGttOayPxKUiuLMKZRJlUEH7ssyXCawVeBUf34B5NAy172aqdm3WGsQkFITOQgCTjKddYXn7Fs2rZow3N9YCkbYhoweoFyndhdF9ST8NmMgpFm3VfocYgNKukGI1gi2LjYoRdyPtdjGK1jwW3KKqyNWuOfkQVNxCg6c9xvQDqnbxiDLRfySn8HOQ9ElsXlN9LIv8PGN07EKKcbkyxsSXmYWHfwn8dOnzeNdL4OFiYNyLyB51YC4cukVROhMKfBbv3Vam6PgObmU4Jq2HF5xEru4MPORt741s8im84oP6.OqDC3SUJ7TSNV1NYii5BOONidacLifUfdaRGwjD05XNXdMCWlulnDCD4CWy7kFEAwA8pqxx9lCfqaA7ezK6054DLhtk0gsWu7gQ3oTjg1fZXinIiI2fLmxXhyisoFrudzwqryhwSmBQMAz3eVkdeyouJTgphFrbXjWnRYEk41iNXT275h68j3EtxSDqOpCZi4kqcuBUPltjS063FEYXa1JKzHThUQFpGVP2wg6doEWaNPAadjBBvOK7Ja6SEIONmiDNa3AfKqYgWoKGRyhQ2fFCZjnx53d7EgVRdBDdVxHhX6P7RghHZcAZ7d5cODz9d7b6IZWbyVDOj4Zd8RkRNQN"}, "user": {}}
保存到文件和从文件加载
- 将以下内容添加到上面的获取令牌示例代码的末尾,然后使用添加内容再次运行它。
# save token to file
with open('farmbot_authorization_token.json', 'w') as f:
f.write(json.dumps(TOKEN))
print('token saved to file')
- 当示例中出现以下行时,将其替换:
# TOKEN = ...
- 和:
# load token from file
with open('farmbot_authorization_token.json', 'r') as f:
TOKEN = json.load(f)
获取最新文章: 扫一扫右上角的二维码加入“创客智造”公众号