python中用token简单的登录_python oauth2 token

python中用token简单的登录_python oauth2 token在 Python 中读取 token 值通常有以下几种方法 从响应头中获取 token 使用 requests 库发送 HTTP 请求 并从响应头中提取 token 值 pythonimport requests url http xxx nhf cn api businessAcco v1 4 userLogin data phoneNum

在Python中读取token值通常有以下几种方法:

从响应头中获取token:

使用`requests`库发送HTTP请求,并从响应头中提取token值。

 import requests url = 'http://xxx.nhf.cn/api/businessAccountInfo/v1.4/userLogin' data = {'phoneNum': '', 'password': ''} response = requests.post(url, json=data) token = response.headers['token'] 

从响应体中获取token:

如果token存在于响应体的字典数据中,可以直接从响应体中提取。

 import requests url = 'http://xxx.nhf.cn/api/fresh/v1.4/ordersList' data = {'pageNo': 1, 'pageSize': 10} headers = {'token': token} response = requests.post(url, json=data, headers=headers) print(response.json()) 

使用第三方库获取token:

例如,使用`requests_oauthlib`或`requests_http_auth`库处理认证流程。

从环境变量中获取token:

使用`os`模块读取环境变量中的token值。

 import os token = os.environ.get('TOKEN') 

通过Selenium获取token:

使用Selenium登录并获取token值,通常token会存储在localStorage或sessionStorage中。

 from seleniumwire import webdriver driver = webdriver.Chrome() agent = driver.requests for request in agent: if request.url == 'www.aaaa.com': print(request.url, request.headers) 

从配置文件中读取token:

将token值保存到YAML或其他配置文件中,然后读取。

 import yaml def write_token(res): curPath = os.path.abspath(os.path.dirname(__file__)) yamlPath = os.path.abspath(os.path.dirname(curPath) + os.path.sep + 'configs/access_token.yml') tokenValue = {'access_token': res['access_token']} with open(yamlPath, 'w', encoding='utf-8') as f: yaml.dump(tokenValue, f) def read_token(): yamlPath = os.path.abspath(os.path.dirname(__file__)) + os.path.sep + 'configs/access_token.yml' with open(yamlPath, 'r', encoding='utf-8') as f: token_data = yaml.safe_load(f) return token_data['access_token'] 

选择合适的方法读取token取决于你的具体需求和应用场景。请根据你的情况选择最适合的方法

编程小号
上一篇 2025-01-26 18:56
下一篇 2025-05-22 15:07

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/61301.html