python-3.x - Flask:如何验证一次并将请求对象用于所有服务器请求
问题描述
我在用户发出请求时使用烧瓶和 Web 请求我在内部为每个传入的请求向第三方 API 发出 2 个请求,此 API 需要基本身份验证。
我的问题是我如何才能全局设置一次基本身份验证。然后对所有用户使用 requests 对象:例如,调用我做的第三方 API:
username = "AA"
password ="XXX"
file_repo_api1 = f'https://api.foo.org/api/auth'
file_response1 = requests.get(file_repo_api1, auth=HTTPBasicAuth(username, password))
page_json1 = file_response1.json()
file_repo_api2 = f'https://api.foo.org/api/info'
file_response2 = requests.get(file_repo_api2, auth=HTTPBasicAuth(username, password))
page_json2 = file_response2.json()
我可以全局设置“auth=HTTPBasicAuth(用户名,密码)”部分吗?
解决方案
requests.Session
根据此处的文档,您应该可以使用它
s = requests.Session()
s.auth = ('user', 'pass')
s.get('https://api.foo.org/api/info')
推荐阅读
- python - Pycharm Project 默认解释器与我的 Python 系统默认安装不匹配?
- javascript - 我可以使用一个功能验证和防止不同输入的数字超过特定值吗?
- eclipse - Eclipse Java 11 看不到旧版本 (java 8) 的外部库
- swift - 在 Swift 中以编程方式居中按钮
- angular - 在量角器中处理警报
- java - 有什么方法可以让我通过JNA调用需要root权限的动态库吗?
- html - HTML DOM API 之间的差异
- python - python re字符串长度(3-4)最大
- javascript - 引导警报 div
- java - Antlr3:为限定名称构建解析树