我有一个 GAE restful 服务,需要使用管理员帐户登录。而我正在用 Python 编写一个自动化脚本来测试这个服务。这个脚本只是执行一个 HTTP POST,然后检查返回的响应。对我来说困难的部分是如何将测试脚本验证为管理员用户。
我创建了一个管理员帐户用于测试目的。但我不确定如何在测试脚本中使用该帐户。有没有办法让我的测试脚本使用 oath2 或其他方法将自己验证为测试管理员帐户?
可以使用 oauth2 来验证测试脚本作为测试管理员帐户。以下是有关如何执行此操作的步骤:
google-auth-oauthlib
库来验证您的应用程序。google-auth-oauthlib
库的示例代码:from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
# This OAuth 2.0 access scope allows for full read/write access.
SCOPE = ["https://www.googleapis.com/auth/cloud-platform"]
def main():
"""Creates and stores credentials in a local file.
Returns:
Credentials, the obtained credentials.
"""
creds, _ = InstalledAppFlow.run_local_server(
scopes=SCOPE, json_path='credentials.json')
# Save the credentials for the next run
with open('credentials.json', 'w') as token:
token.write(creds.to_json())
return creds
def get_creds():
"""Retrieves credentials from a file if they exist.
Returns:
Credentials, credentials retrieved from the file.
"""
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('credentials.json'):
creds = Credentials.from_authorized_user_file('credentials.json', SCOPE)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
creds = main()
return creds
def make_request(url, creds):
"""Makes a GET request to the URL using credentials.
Args:
url: The URL to make the request to.
creds: The credentials to use for the request.
Returns:
The response from the request.
"""
session = RequestsSession()
session.auth = creds
response = session.get(url)
return response
if __name__ == '__main__':
creds = get_creds()
response = make_request('https://example.com/', creds)
print(f'Response: {response}')
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。