Azure HTTP 函数路由

问题描述 投票:0回答:1

我正在尝试将 Flask API 转换为 azure 函数。

@app.route(route="{directory_name}/static/{file_path:path}", auth_level=func.AuthLevel.ANONYMOUS,
           methods=[func.HttpMethod.GET])
def serve_static(req: func.HttpRequest) -> func.HttpResponse:
    ....

在 Flask 中,带有

{file_path:path}
的路线有效,但在 azure 函数中我收到此错误: Microsoft.AspNetCore.Routing:创建名为“serve_static”和模板“{directory_name}/static/{file_path:path}”的路由时出错。 Microsoft.AspNetCore.Routing:路由“{directory_name}/static/{file_path:path}”上的约束条目“file_path”-“path”无法由“DefaultInlineConstraintResolver”类型的约束解析器解析。

我寻找类似的东西,但我似乎找不到有用的东西。

python-3.x azure-functions
1个回答
0
投票

您遇到的问题是 Azure Functions HTTP 触发器不支持像 Flask 那样的自定义路由模式。相反,您需要创建一个路由,然后在您的函数中自行解析 URL。

下面是 HTTP 触发函数,用于创建路由并处理函数内 URL 的解析。

serve_static/

init.py: {file_path:path}

serve_static/function.json :

import azure.functions as func from urllib.parse import unquote import os def main(req: func.HttpRequest) -> func.HttpResponse: directory_name = req.route_params.get('directory_name') file_path = req.route_params.get('file_path', '') file_path = unquote(file_path) static_folder = os.path.join(os.path.dirname(__file__), 'static') full_path = os.path.join(static_folder, directory_name, file_path) if not os.path.commonprefix([static_folder, full_path]) == static_folder: return func.HttpResponse("Invalid file path", status_code=400) try: with open(full_path, 'rb') as f: file_content = f.read() return func.HttpResponse(file_content, mimetype="application/octet-stream") except FileNotFoundError: return func.HttpResponse(f'File not found: {full_path}', status_code=404) except Exception as e: return func.HttpResponse(f'Error: {str(e)}', status_code=500)

浏览器输出:

我已经下载了example.txt文件,HTTP触发函数的URL如下,

{ "scriptFile": "__init__.py", "bindings": [ { "authLevel": "anonymous", "type": "httpTrigger", "direction": "in", "name": "req", "route": "{directory_name}/static/{*file_path}", "methods": ["get"] }, { "type": "http", "direction": "out", "name": "$return" } ] }

enter image description here

终端输出:

以下HTTP触发函数代码运行成功如下。

enter image description here下面是我的 example.txt 文件中的数据。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.