使用python编写一个获取token的接口

import requests
from requests.auth import HTTPBasicAuth

def get_token():
    """
    获取 token 的逻辑
    """
    url = "https://devxxxxxxxxtion/v2/token"   # 替换为实际的 token 获取 URL
    client_id = "hAixxxeMPNxxxxGjF9k"  # 替换为实际的 client_id
    client_secret = "xxxxx"  # 替换为实际的 client_secret
    scope = 'data:read data:write'
    params = {
        'grant_type': 'client_credentials',
        'scope' : scope
    }
    response = requests.post(url, auth=HTTPBasicAuth(client_id, client_secret), params=params)

    if response.status_code == 200:
        token = response.json().get("access_token")
        return token
    else:
        raise Exception("Failed to get token: {}".format(response.text))

if __name__ == "__main__":
    try:
        token = get_token()
        print("Access token:", token)
    except Exception as e:
        print(e)

以上是一个简单的例子。

当然,如果项目中已经有能直接用的的接口,无需再重新编写,可以直接引用:

import fyclient as forge
from fyclient.auth import get_access_token
def create_acp_job_request(payload, worker, moniker):
env = MK.get_env_by_moniker(moniker).lower()
if env == 'dev' or env == 'staging':
forge.g_config.key = os.getenv('FORGE_TEST_CLIENT_ID')
forge.g_config.secret = os.getenv('FORGE_TEST_CLIENT_SECRET')
forge.g_config.host = 'https://develxxxxx.com'
access_token, _ = get_access_token(scope='data:write')

posted @ 2024-11-07 10:24  安琪儿一直在  阅读(26)  评论(0编辑  收藏  举报