简体   繁体   中英

Flask `before_request` context functions on Google Cloud Functions

I'm trying to use Flask context classes and functions on Google Cloud Functions. 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. and just using @before_request , but that doesn't seem to work. 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.

Thanks!

It's not currently possible to operate outside of the function context in Cloud Functions. Cloud Functions do not have access to the underlying 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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