如何在第二代 Google Cloud Function 中使用会话?
当我尝试设置会话时出现错误。
session['logged_in'] = True
给出错误:
运行时错误:会话不可用,因为没有密钥 放。将应用程序上的 Secret_key 设置为唯一的并且 秘密。
main.py
import functions_framework
from flask import session
@functions_framework.http
def hello_http(request):
"""HTTP Cloud Function.
Args:
request (flask.Request): The request object.
<https://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data>
Returns:
The response text, or any set of values that can be turned into a
Response object using `make_response`
<https://flask.palletsprojects.com/en/1.1.x/api/#flask.make_response>.
"""
request_json = request.get_json(silent=True)
request_args = request.args
# Sessions
session['logged_in'] = True
# Hello
if request_json and 'name' in request_json:
name = request_json['name']
elif request_args and 'name' in request_args:
name = request_args['name']
else:
name = 'World'
return 'Hello {}!'.format(name)
需求.txt
flask
functions-framework==3.*
问题在于您使用的是 Flask 中间件而没有 Flask,正如您所注意到的那样,这不起作用。
您可以像自己创建 cookie 一样简单。我不会涉及用户管理,只会涉及读/写 cookie。
请注意,应该对 cookie 值进行加密和解密,但我也不打算涉及这一点。
下面是使用 Flask 的 Response 类设置和获取 cookie 的极其简单的逻辑,因为这是 Cloud Functions (CF) 接受的有效响应对象。我也通过使用
make_response
来简化其用法
另请注意,您将 CF 用于不该用于的用途,根据 此处的 CF 用例。 我建议为此使用 App Engine 或 Cloud Run,因为它们是更传统的无服务器选项,更适合管理用户会话。
import functions_framework
from flask import make_response
@functions_framework.http
def hello_http(request):
# the line below returns None if the specific cookie has not been set
cookie = request.cookies.get('logged_in')
# test if user logged in:
if cookie:
# do other magic here, now just returning the string from the cookie
# you should do some testing here that Flask Session do behind the scenes,
# like actually testing the value of the cookie (which should be encrypted)
return cookie
else:
# set cookies by building a proper response as per
# https://cloud.google.com/functions/docs/writing/write-http-functions
# note that login logic should reside here
resp = make_response("whatever response")
resp.set_cookie('logged_in', 'this value should actually be encrypted')
return resp
第一次运行 CF 时,它找不到 cookie,因此它使用
make_response
设置它。第二次运行 CF 时,它会找到 cookie,并简单地返回它的值。