我正在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应用程序不会处理该请求.