首页 > 解决方案 > 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(用户名,密码)”部分吗?

标签: python-3.xapiflask

解决方案


requests.Session根据此处的文档,您应该可以使用它

s = requests.Session()
s.auth = ('user', 'pass')
s.get('https://api.foo.org/api/info')

推荐阅读