我们在 GCP Functions 上部署了一个 python 函数,它基本上接收 HTTP POST JSON,并调用另一个系统进行一些处理。这个其他系统返回一个 JSON,我们将 JSON 发送回原始调用者。
该函数在 128mb 内存下运行良好,但在我们有了一位新客户后,他们不断调用该函数,现在 GCP 抛出超出内存限制的错误并中断了进程。
我知道如果客户在两次通话之间等待几分钟,内存就会恢复正常,但我不能要求他们这样做。
我的问题是,在对函数进行各种顺序调用后,是否有办法防止这种大量内存增加?或者任何替代方法来检测它是否达到限制并发回超时错误?
我的部分代码
#!venv/bin/python
from flask import Flask, request, Response,jsonify,make_response
import json
import requests
from functools import wraps
import hashlib
from google.cloud import firestore
import datetime
app = Flask(__name__)
app.secret_key = b'NOTHERE'
def check_auth(username, password):
pwd = hashlib.sha1(str(password).encode('utf-8')).hexdigest()
db = firestore.Client()
users_ref = db.collection('XXX')
doc_ref = users_ref.document(username)
try:
doc = doc_ref.get()
dic = doc.to_dict()
return pwd == dic['password']
except:
pass
return False
def authenticate():
"""Sends a 401 response that enables basic auth"""
return Response(
'Please Login', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
#main function that google calls
@requires_auth
def brokering(request):
db = firestore.Client()
if request.method == 'POST':
......... here I do some write/reads on the firestore db
直到崩溃的内存图(130 次调用)
请您参考如下方法:
我会尽可能多地移动到功能之外。例如,您当前正在为每个请求创建两个 firestore.Client() 实例,一个在 brokering 中,一个在 check_auth 中.您应该将它移到函数定义之外,并在函数内重用单个客户端实例。
您还会做一些不必要的事情,例如初始化 Cloud Functions 未使用的整个 Flask 应用程序,但会减少您的内存开销。
我会把你的整个函数重写成这样:
from flask import request, Response
from functools import wraps
import hashlib
from google.cloud import firestore
db = firestore.Client()
users_ref = db.collection('XXX')
def check_auth(username, password):
pwd = hashlib.sha1(str(password).encode('utf-8')).hexdigest()
doc_ref = users_ref.document(username)
try:
return pwd == doc_ref.get().to_dict()['password']
except:
pass
return False
def authenticate():
"""Sends a 401 response that enables basic auth"""
return Response(
'Please Login', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
@requires_auth
def brokering(request):
if request.method == 'POST':
... # here I do some write/reads on the firestore db
