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

查看:67
本文介绍了在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中.

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 Functions python是beta版是有原因的?

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天全站免登陆