我正在try 使用Python脚本向Google Apps Script Web应用发送POST请求.虽然在Web浏览器中访问Web应用程序的URL可以很好地处理GET请求,但使用Python发送POST请求会导致401 Unauthorized错误.

身份验证过程如下:

from google_auth_oauthlib.flow import InstalledAppFlow

SCOPES = ['openid', 'https://www.googleapis.com/auth/script.projects', 'https://www.googleapis.com/auth/script.webapp.deploy']
CLIENT_SECRETS_FILE = 'client_secret.json'

flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES, redirect_uri='http://localhost:80/')
credentials = flow.run_local_server(port=80)

headers = {
    'Authorization': f'Bearer {credentials.token}',
    'Content-Type': 'application/json',
}

# Checking token validity
if credentials.valid:
    print("Token is valid.")
else:
    print("Token is not valid.")

# Checking if the token has expired
if credentials.expired:
    print("Token has expired.")
else:
    print("Token is still valid.")

print("Scopes granted to the token:", credentials.scopes)
print("Access token:", credentials.token)


    try:
       response = requests.post(url, headers=headers1, json={"text": "hello from python with OAuth"})
       response.text
       response.raise_for_status()  # 400 or 500 Error
    except requests.exceptions.HTTPError as err:
        print(f"HTTP error occurred: {err}")  # HTTP Error
    except Exception as err:
        print(f"An error occurred: {err}")  # Other Error 

Apps Script Web应用的appsscript.json设置如下:

{
  "timeZone": "Asia/Seoul",
  "dependencies": {},
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8",
  "webapp": {
    "executeAs": "USER_ACCESSING",
    "access": "DOMAIN"
  }
}

令牌是有效的,并且授予的范围没有问题.根据Google Cloud Console,用户拥有所有者权限,并且启用了Apps Script API.

尽管有这些设置和条件,我还是不能理解为什么POST请求会失败.Web应用程序的doPost函数被配置为处理JSON类型的POST数据.如果您能就我可能遗漏的内容提出建议,我将不胜感激.

谢谢.

我try 了什么:

我使用一个Python脚本向Google Apps脚本Web应用程序发送了一个POST请求.我使用OAuth 2.0进行身份验证,将访问令牌包含在报头中,然后发送请求.Google Apps脚本中的doPost函数被设置为接收和处理JSON数据.

我所期待的:

在成功完成身份验证过程并获得有效的访问令牌后,我预计Web应用程序会收到POST请求并做出适当的响应.

实际发生了什么:

虽然通过带有GET请求的Web浏览器访问Web应用程序运行良好,但通过Python脚本发送POST请求会导致401未经授权的错误.因此,Web应用程序不会处理该请求.

推荐答案

关于状态代码401,它意味着The HyperText Transfer Protocol (HTTP) 401 Unauth或ized response status code indicates that the client request has not been completed because it lacks valid authentication credentials f或 the requested resource..Ref

为了请求有访问令牌的Web应用,在现阶段,需要包括Drive API的范围.我猜,当我看到你的展示 playbook 时,这可能是因为你现在的问题的原因.那么,下面的修改如何?

出发地:

SCOPES = ['openid', 'https://www.googleapis.com/auth/script.projects', 'https://www.googleapis.com/auth/script.webapp.deploy']

致:

SCOPES = ["https://www.googleapis.com/auth/drive"]

SCOPES = ["https://www.googleapis.com/auth/drive.readonly"]

或, if you are required to use the scopes of 'openid', 'https://www.googleapis.com/auth/script.projects', 'https://www.googleapis.com/auth/script.webapp.deploy', please modify as follows.

SCOPES = ["https://www.googleapis.com/auth/drive", 'openid', 'https://www.googleapis.com/auth/script.projects', 'https://www.googleapis.com/auth/script.webapp.deploy']

SCOPES = ["https://www.googleapis.com/auth/drive.readonly", 'openid', 'https://www.googleapis.com/auth/script.projects', 'https://www.googleapis.com/auth/script.webapp.deploy']

注:

  • Unf或tunately, I have no inf或mation about your Google Apps Script. So, this answer is f或 modifying your showing Python script. And, it supposes that your Google Apps Script w或ks fine. Please be careful about this.

参考资料:

Python相关问答推荐

将整组数组拆分为最小值与最大值之和的子数组

根据另一列中的nan重置值后重新加权Pandas列

图像 pyramid .难以创建所需的合成图像

两个pandas的平均值按元素的结果串接元素.为什么?

在Python中动态计算范围

如何在WSL2中更新Python到最新版本(3.12.2)?

在np数组上实现无重叠的二维滑动窗口

Pandas Loc Select 到NaN和值列表

多处理队列在与Forking http.server一起使用时随机跳过项目

Python Pandas—时间序列—时间戳缺失时间精确在00:00

如何在Gekko中使用分层条件约束

我对这个简单的异步者的例子有什么错误的理解吗?

根据Pandas中带条件的两个列的值创建新列

如何使用Azure Function将xlsb转换为xlsx?

如何在验证文本列表时使正则表达式无序?

解决Geopandas和Altair中的正图和投影问题

如何在PythonPandas 中对同一个浮动列进行逐行划分?

在matplotlib中重叠极 map 以创建径向龙卷风图

函数()参数';代码';必须是代码而不是字符串

Django REST框架+Django Channel->;[Errno 111]连接调用失败(';127.0.0.1';,6379)