我正在尝试捕获SQLAlchemy错误,并在执行错误时执行Google Apps脚本,该脚本已部署为API可执行文件。
示例错误:
[SQL: INSERT INTO mytbl (id, attr) VALUES (%(id)s, %(attr)s)]
[parameters: ({'id': 177, 'attr': u'dog'}, {'id': 178, 'attr': u'cat'})]
(Background on this error at: http://sqlalche.me/e/gkpj)
# omitted Traceback
IntegrityError: (psycopg2.errors.UniqueViolation) duplicate key value violates unique constraint "mytbl_pkey"
DETAIL: Key (id)=(177) already exists.
.gs在出错时执行。独立运行时,运行正常。
function myfunct() {
ss = SpreadsheetApp.openById("my_spreadsheet_id")
ss.getRange('A10').setValue('Error');
}
.py调用.gs
# omitted libraries
try:
# my stuff to get data and insert in db
except psycopg2.Error as e:
logging.exception(str(e))
error = e.pgcode
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.currentonly']
def get_scripts_service():
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# 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:
flow = InstalledAppFlow.from_client_secrets_file(
'/my/path/oauth_client_secret.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
return build('script', 'v1', credentials=creds)
service = get_scripts_service()
SCRIPT_ID = "my_exec_api_id"
request = {"function": "myfunct"}
try:
response = service.scripts().run(body=request, scriptId=SCRIPT_ID).execute()
if 'error' in response:
# The API executed, but the script returned an error.
# Extract the first (and only) set of error details. The values of
# this object are the script's 'errorMessage' and 'errorType', and
# an list of stack trace elements.
error = response['error']['details'][0]
print("Script error message: {0}".format(error['errorMessage']))
if 'scriptStackTraceElements' in error:
# There may not be a stacktrace if the script didn't start
# executing.
print("Script error stacktrace:")
for trace in error['scriptStackTraceElements']:
print("\t{0}: {1}".format(trace['function'],
trace['lineNumber']))
except errors.HttpError as error:
print(e.content)
sys.exit(1)
这不会输出任何错误或执行.gs脚本。我是Python和Execution API的新手。即使在深入研究错误处理之后,我仍可能会丢失一些明显的东西。