【问题标题】:Injecting a Flask Request into another Flask App将 Flask 请求注入另一个 Flask 应用程序
【发布时间】: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 并实际向您拥有的另一个 appview 发出请求。
  • 不太确定我是否关注你。我在帖子中添加了更多细节,进一步解释了我正在尝试做的事情。

标签: python flask google-cloud-platform google-cloud-functions


【解决方案1】:

我不推荐这种方法,但通过滥用请求堆栈并重写当前请求并重新调度它,这在技术上是可行的。

但是,您仍然需要执行某种类型的自定义“路由”来正确设置 url_rule,因为来自 GCF 的传入请求不会拥有它(除非您通过请求明确提供它):

from flask import Flask, _request_ctx_stack
from werkzeug.routing import Rule

app = Flask(__name__)

@app.route('/hi')
def hi(*args, **kwargs):
    return 'Hi!'

def say_hello(request):
    ctx = _request_ctx_stack.top
    request = ctx.request
    request.url_rule = Rule('/hi', endpoint='hi')
    ctx.request = request
    _request_ctx_stack.push(ctx)
    return app.dispatch_request()

【讨论】:

  • 谢谢达斯汀。我会试试这个。我发现跨应用程序调度在本地工作(请参阅我添加到问题中的编辑 2)。如果 GCF 也支持类似的东西就好了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-04
  • 2017-01-31
  • 2019-04-20
相关资源
最近更新 更多