在 GCP 功能中使用 Flask 路由? [英] Using Flask Routing in GCP Function?

查看:29
本文介绍了在 GCP 功能中使用 Flask 路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用 python 从单个 GCP 云函数提供多个路由.虽然 GCP 函数实际上在幕后使用了 Flask,但我似乎无法弄清楚如何使用 Flask 路由系统从单个云函数提供多个路由.

I am looking to serve multiple routes from a single GCP cloud function using python. While GCP Functions actually use flask under the hood, I can't seem to figure out how to use the flask routing system to serve multiple routes from a single cloud function.

我正在做一个非常小的项目,所以我写了一个我自己的快速路由器,它运行良好.现在我更多地使用 GCP 函数,我要么想弄清楚如何使用 Flask 路由器,要么在我的手卷版本上投入更多时间,也许开源它,尽管当它非常有用时它似乎是多余的Flask 路由的关闭副本,因此如果此功能不存在,最好将其直接添加到 Flask.

I was working on a very small project, so I wrote a quick router of my own which is working well. Now that I'm using GCP Functions more, I'd either like to figure out how to use the Flask router or invest more time on my hand rolled version and perhaps open source it, though it would seem redundant when it would be a very close copy of flask's routing, so perhaps it would be best to add it directly to Flask if this functionality doesn't exist.

有没有人有这个问题的经验?我猜我缺少一个隐藏在 Flask 中某个地方的简单函数,但如果不是,这似乎是一个非常大/常见的问题,尽管我猜 GCP 函数 python 是测试版是有原因的?

Does anyone have any experience with this issue? I'm guessing I'm missing a simple function to use that's hidden in Flask somewhere but if not this seems like a pretty big/common problem, though I guess GCP Functions python is beta for a reason?

如果可能的话,我想使用 Flask 的手卷版本的删节示例:

Abridged example of my hand rolled version that I'd like to use Flask for if possible:

router = MyRouter()

@router.add('some/path', RouteMethod.GET)
def handle_this(req):
    ...


@router.add('some/other/path', RouteMethod.POST)
def handle_that(req):
    ...


# main entry point for the cloud function
def main(request):
    return router.handle(request)

推荐答案

以下解决方案对我有用:

Following solution is working for me:

import flask
import werkzeug.datastructures


app = flask.Flask(__name__)


@app.route('some/path')
def handle_this(req):
    ...


@app.route('some/other/path', methods=['POST'])
def handle_that(req):
    ...


def main(request):
    with app.app_context():
        headers = werkzeug.datastructures.Headers()
        for key, value in request.headers.items():
            headers.add(key, value)
        with app.test_request_context(method=request.method, base_url=request.base_url, path=request.path, query_string=request.query_string, headers=headers, data=request.data):
            try:
                rv = app.preprocess_request()
                if rv is None:
                    rv = app.dispatch_request()
            except Exception as e:
                rv = app.handle_user_exception(e)
            response = app.make_response(rv)
            return app.process_response(response)

基于 http://flask.pocoo.org/snippets/131/

这篇关于在 GCP 功能中使用 Flask 路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆