为什么Google Cloud Functions返回错误:无法处理请求?

时间:2019-05-09 22:15:00

标签: python http google-cloud-platform python-requests google-cloud-functions

我在Python中有一个GCF,每9小时刷新一次访问令牌。 当我测试该功能时,将获得Response 200,成功!

但是,当我发送POST请求或尝试通过Google Scheduler调用该函数时,在前3次或多次出现错误Error: could not handle the request。发送几个请求后,函数将被执行。为什么?

Scheduler configuration

我的功能如下:

from os import getenv
import requests
import pymysql
import json
from pymysql.err import OperationalError


CONNECTION_NAME = getenv('INSTANCE_CONNECTION_NAME', '')
DB_USER = getenv('MYSQL_USER', '')
DB_PASSWORD = getenv('MYSQL_PASSWORD', '')
DB_NAME = getenv('MYSQL_DATABASE', '')

mysql_config = {
  'user': DB_USER,
  'password': DB_PASSWORD,
  'db': DB_NAME,
  'charset': 'utf8mb4',
  'cursorclass': pymysql.cursors.DictCursor,
  'autocommit': True
}

mysql_conn = None


def __get_cursor():
    try:
        return mysql_conn.cursor()
    except OperationalError:
        mysql_conn.ping(reconnect=True)
        return mysql_conn.cursor()


def authMonzo(request):
    global mysql_conn
    global endpoint

    endpoint = ''

    if not mysql_conn:
        try:
            mysql_conn = pymysql.connect(**mysql_config)
        except OperationalError:
            mysql_config['unix_socket'] = f'/cloudsql/{CONNECTION_NAME}'
            mysql_conn = pymysql.connect(**mysql_config)

    with __get_cursor() as cursor:   
        cursor.execute("SELECT * FROM TOKENS ORDER BY ID DESC LIMIT 1")
        result = cursor.fetchall()

        clientSecret = result[...]
        clientId = result[...]
        refreshToken = result[...]

        # Change the last refresh token for a new access token
        tokenRequest = requests.post(endpoint, data={'grant_type': 'refresh_token', 'client_id': clientId, 'client_secret': clientSecret, 'refresh_token': refreshToken})
        tokenJson = json.loads(tokenRequest.content)

        print(tokenJson)

        # Assing the values to variables
        accessToken = tokenJson['access_token']
        refreshToken = tokenJson['refresh_token']
        scope = tokenJson['scope']
        clientId = tokenJson['client_id']
        expiresIn = tokenJson['expires_in']
        userId = tokenJson['user_id']
        tokenType = tokenJson['token_type']

        # Insert the new token on the table tokens
        SQLToken = ("INSERT INTO TOKENS (CLIENT_SECRET, ACCESS_TOKEN, REFRESH_TOKEN, TOKEN_TYPE, USER_ID, CLIENT_ID, EXPIRES_IN, SCOPE) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)")
        Values = (clientSecret, accessToken, refreshToken, tokenType, userId, clientId, expiresIn, scope)

        cursor.execute(SQLToken, Values)
        mysql_conn.close()

    return str(accessToken)

0 个答案:

没有答案