简体   繁体   English

Google Cloud Functions 上的 Flask `before_request` 上下文函数

[英]Flask `before_request` context functions on Google Cloud Functions

I'm trying to use Flask context classes and functions on Google Cloud Functions.我正在尝试在 Google Cloud Functions 上使用 Flask 上下文类和函数。 Here's simple code of what I'm trying to do:这是我正在尝试做的简单代码:

import time
from flask import request, jsonify, g

@app.before_request
def before_request():
    g.start = time.time()

@app.after_request
def after_request(response):
    if ((response.json) and (response.response) and (200 <= response.status_code < 300)):
        response.json['execution_time'] = time.time() - g.start
        response.set_data(bytes(json.dumps(response.json), 'utf-8'))
    return response

def hello_world(request):
    response = jsonify({"status": "success", "message": "Hello World!"})
    response.status_code = 200
    return response

I've tried removing app.我试过删除app. and just using @before_request , but that doesn't seem to work.并且只是使用@before_request ,但这似乎不起作用。 Any idea if this is supported?知道这是否受支持吗?

Also, yes, I know that I could just add an execution_time parameter to each of my responses, but a) it would be nice to set it globally, and b) there are other use cases for the before_request and after_request functions.另外,是的,我知道我可以为每个响应添加一个execution_time参数,但是 a) 全局设置它会很好,并且 b) before_requestafter_request函数还有其他用例。

Thanks!谢谢!

It's not currently possible to operate outside of the function context in Cloud Functions.目前无法在 Cloud Functions 中的函数上下文之外进行操作。 Cloud Functions do not have access to the underlying app . Cloud Functions 无权访问底层app

You may want to consider using Cloud Run instead, which would let you define a complete Flask app and use @app.before_request and @app.after_request .您可能需要考虑改用Cloud Run ,它可以让您定义一个完整的 Flask app并使用@app.before_request@app.after_request

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM