如何在 Python 测试脚本中访问需要登录的 GAE 服务

本文介绍如何使用OAuth2验证Python脚本作为管理员访问GAERESTful服务,涉及创建OAuth客户端、使用google-auth-oauthlib进行授权的过程。
摘要由CSDN通过智能技术生成

在这里插入图片描述

1、问题背景

我有一个 GAE restful 服务,需要使用管理员帐户登录。而我正在用 Python 编写一个自动化脚本来测试这个服务。这个脚本只是执行一个 HTTP POST,然后检查返回的响应。对我来说困难的部分是如何将测试脚本验证为管理员用户。

我创建了一个管理员帐户用于测试目的。但我不确定如何在测试脚本中使用该帐户。有没有办法让我的测试脚本使用 oath2 或其他方法将自己验证为测试管理员帐户?

2、解决方案

可以使用 oauth2 来验证测试脚本作为测试管理员帐户。以下是有关如何执行此操作的步骤:

  1. 使用您的测试管理员帐户登录 Google Cloud Console。
  2. 导航到“API 和服务”>“凭据”。
  3. 单击“创建凭据”>“OAuth 客户端 ID”。
  4. 在“应用程序类型”下,选择“桌面应用程序”。
  5. 在“名称”下,输入您的应用程序的名称。
  6. 单击“创建”。
  7. 您将看到一个带有客户端 ID 和客户端机密的屏幕。复制这两项内容。
  8. 在您的测试脚本中,使用 google-auth-oauthlib 库来验证您的应用程序。
  9. 以下是使用 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}')
  1. 运行您的测试脚本。如果成功,您应该会看到一个带有成功消息的响应。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值