有没有办法将 Flask 请求对象注入到不同的 Flask 应用程序中。这就是我想做的:
app = flask.Flask(__name__)
@app.route('/foo/<id>')
def do_something(id):
return _process_request(id)
def say_hello(request):
# request is an instance of flask.Request.
# I want to inject it into 'app'
我正在尝试使用 Google Cloud Functions,其中say_hello()
是由云运行时调用的函数。它接收到一个flask.Request
作为参数,我想然后通过我自己的一组路由进行处理。
我尝试了以下方法,但不起作用:
def say_hello(request):
with app.request_context(request.environ):
return app.full_dispatch_request()
这会对所有请求响应 404 错误。
Edit:
简单的实现方法say_hello()
如下:
def say_hello(request):
if request.method == 'GET' and request.path.startswith('/foo/'):
return do_something(_get_id(request.path))
flask.abort(404)
这本质上需要我自己编写路由匹配逻辑。我想知道是否有办法避免这样做,而是使用 Flask 的内置装饰器和路由功能。
Edit 2:
有趣的是,跨应用程序的调度在本地工作:
app = flask.Flask(__name__)
# Add app.routes here
functions = flask.Flask('functions')
@functions.route('/', defaults={'path': ''})
@functions.route('/<path:path>', methods=['GET', 'POST', 'PUT', 'DELETE'])
def catch_all(path):
with app.request_context(flask.request.environ):
return app.full_dispatch_request()
if __name__ == '__main__':
functions.run()
但同样的技术似乎不适用于 GCF。