adj*_*ant 6 flask python-3.x google-cloud-platform google-cloud-functions
我希望使用python从单个GCP云功能提供多个路由。虽然GCP功能实际上在内部使用了Flask,但我似乎无法弄清楚如何使用Flask路由系统通过单个云功能为多个路由提供服务。
我当时在做一个很小的项目,所以我写了一个自己的快速路由器,效果很好。现在,我更多地使用了GCP功能,我想弄清楚如何使用Flask路由器,或者在我的手动版本和开放源代码上投入更多时间,尽管当它看起来非常实用时似乎显得多余了。烧瓶路由的紧密副本,因此,如果不存在此功能,最好将其直接添加到Flask中。
有人对此问题有经验吗?我猜想我缺少一个简单的函数来使用它隐藏在Flask中的某个地方,但是如果不是这样,这似乎是一个很大的/常见的问题,尽管我猜GCP Functions python是beta版是有原因的?
编辑:如果可能的话,我想使用Flask的手卷版本的简化示例:
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)
Run Code Online (Sandbox Code Playgroud)
以下解决方案对我有用:
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)
Run Code Online (Sandbox Code Playgroud)
基于http://flask.pocoo.org/snippets/131/
| 归档时间: |
|
| 查看次数: |
1371 次 |
| 最近记录: |