【发布时间】:2019-01-30 09:59:46
【问题描述】:
有没有办法将 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 错误响应所有请求。
编辑:
实现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 的内置装饰器和路由功能。
编辑 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。
【问题讨论】:
-
您的意思是应用程序的多个实例?除此之外,您可能能够逃脱
requests并实际向您拥有的另一个app的view发出请求。 -
不太确定我是否关注你。我在帖子中添加了更多细节,进一步解释了我正在尝试做的事情。
标签: python flask google-cloud-platform google-cloud-functions