Flask `before_request` context functions on Google Cloud Functions

Arthur Sommers :

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!

Dustin Ingram :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=371645&siteId=1