将Flask请求注入另一个Flask应用 [英] Injecting a Flask Request into another Flask App
问题描述
是否可以将Flask请求对象注入到其他Flask应用中.这就是我想要做的:
Is there a way to inject a Flask request object into a different Flask app. This is what I'm trying to do:
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
作为参数,然后我要通过自己的一组路由对其进行处理.
I'm trying this with Google Cloud Functions, where say_hello()
is a function that is invoked by the cloud runtime. It receives a flask.Request
as the argument, which I want to then process through my own set of routes.
我尝试了以下操作,但这不起作用:
I tried the following, which doesn't work:
def say_hello(request):
with app.request_context(request.environ):
return app.full_dispatch_request()
这将对所有请求返回404错误.
This responds with 404 errors for all requests.
实现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的内置装饰器和路由功能.
This essentially requires me to write the route matching logic myself. I'm wondering if there's a way to avoid doing that, and instead use Flask's built-in decorators and routing capabilities.
有趣的是,跨应用程序分派在本地工作:
Interestingly, dispatching across apps work locally:
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.
But the same technique doesn't seem to work on GCF.
推荐答案
我不推荐使用此方法,但是从技术上讲,可以通过滥用请求堆栈并重写当前请求并重新调度它来实现.
I wouldn't recommend this method, but this is technically possible by abusing the request stack and rewriting the current request and re-dispatching it.
但是,您仍然需要执行某种类型的自定义路由"以正确设置url_rule
,因为来自GCF的传入请求将没有该请求(除非您通过请求明确提供了该请求):
However, you'll still need to do some type of custom "routing" to properly set the url_rule
, as the incoming request from GCF won't have it (unless you explicitly provide it via the request):
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()
这篇关于将Flask请求注入另一个Flask应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!