来自 Azure 函数的 Dynamic Cosmos SQL 查询

Dynamic Cosmos SQL query from Azure functions

我们有一个 Cosmos DB,我们正尝试使用 http 触发函数 API 使用不同的参数从中检索数据。 我知道 cosmos 输入绑定,但为此我需要在 function.json 文件中放入我的 SQL 查询,如果查询中存在所有参数,这很好。 问题是,我想根据不同的参数获取数据,并且可能不会为每个查询发送所有这些参数。有没有办法让这个函数 API 足够动态地在 运行 时间内创建 SQL 查询并从 Cosmos 获取数据?

我尝试使用 Cosmos python SDK 而不是使用输入绑定,但出现以下错误。 “没有名为 'azure.cosmos' 的模块”。

当我通常 运行 一个 python 程序访问 cosmos 外部函数时,它工作正常,这告诉我我已经导入了必要的库。但是当从 python 函数调用时,这是失败的。我已经检查过我指向的是正确的解释器 (python 3.8)。

有什么我想念的吗?下面是我的代码:

{

import logging
from azure.cosmos import exceptions, CosmosClient, PartitionKey
import azure.functions as func


def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    name = req.params.get('name')
    if not name:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            name = req_body.get('name')

    if name:
        endpoint = "https://anucosmos123.documents.azure.com:443/"
        key = 'kbN3EzLfxVYUDg4dRG0gtyehgnrD2kM410jyzfUIK1N8dl11tmVkZcig9PKNmccJR89jHdYIeHKnjH7JnMYo6Q=='
        client = CosmosClient(endpoint, key)
        database_name = 'mydb'
        database = client.create_database_if_not_exists(id=database_name)
        container_name= 'mycoll'
        container = database.create_container_if_not_exists(id=container_name,partition_key=PartitionKey(path="/name"),
            offer_throughput=400)

        query = 'SELECT * FROM c WHERE c.name = "Anupam"'
        items = list(container.query_items(query=query, enable_cross_partition_query=True))
        print(items)
        return func.HttpResponse(items, status_code=200)
    else:
        return func.HttpResponse(
             "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
             status_code=200
        )

}

下面是我收到的错误。 {

[2021-02-10T05:05:48.655Z] Worker process started and initialized.[2021-02-10T05:05:48.726Z] Worker failed to function id 89f6dacb-3136-4a73-89f4-7525bdc69fe0.

[2021-02-10T05:05:49.388Z] Result: Failure
Exception: ModuleNotFoundError: No module named 'azure.cosmos'. Troubleshooting Guide: https://aka.ms/functions-modulenotfound
Stack:   File "C:\Program Files\Microsoft\Azure Functions Core Tools\workers\python.8/WINDOWS/X64\azure_functions_worker\dispatcher.py", line 271, in _handle__function_load_request
    func = loader.load_function(
  File "C:\Program Files\Microsoft\Azure Functions Core Tools\workers\python.8/WINDOWS/X64\azure_functions_worker\utils\wrappers.py", line 34, in call
    raise extend_exception_message(e, message)
  File "C:\Program Files\Microsoft\Azure Functions Core Tools\workers\python.8/WINDOWS/X64\azure_functions_worker\utils\wrappers.py", line 32, in call
    return func(*args, **kwargs)
  File "C:\Program Files\Microsoft\Azure Functions Core Tools\workers\python.8/WINDOWS/X64\azure_functions_worker\loader.py", line 76, in load_function
    mod = importlib.import_module(fullmodname)
  File "C:\Users\dell\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "D:\Visual Studio\Projects\Functions1\myhttp1\__init__.py", line 2, in <module>
    from azure.cosmos import exceptions, CosmosClient, PartitionKey
.
[2021-02-10T05:05:49.397Z] Worker failed to function id dc05d956-83c3-44fd-9dfd-304c3f3db8ca.
[2021-02-10T05:05:49.398Z] Result: Failure
Exception: AttributeError: module 'azure.functions' has no attribute 'In'
Stack:   File "C:\Program Files\Microsoft\Azure Functions Core Tools\workers\python.8/WINDOWS/X64\azure_functions_worker\dispatcher.py", line 271, in _handle__function_load_request
    func = loader.load_function(
  File "C:\Program Files\Microsoft\Azure Functions Core Tools\workers\python.8/WINDOWS/X64\azure_functions_worker\utils\wrappers.py", line 32, in call
    return func(*args, **kwargs)
  File "C:\Program Files\Microsoft\Azure Functions Core Tools\workers\python.8/WINDOWS/X64\azure_functions_worker\loader.py", line 76, in load_function
    mod = importlib.import_module(fullmodname)
  File "C:\Users\dell\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "D:\Visual Studio\Projects\Functions1\SBTopicTrigger1\__init__.py", line 5, in <module>
    def main(message: func.ServiceBusMessage, inputdocument: func.In[func.Document], outputSbMsg:func.ServiceBusMessage):

}

We have a Cosmos DB from which we are trying to retrieve data using different parameters using a http triggered function API. I'm aware of the cosmos input binding but for this I need to put in my SQL query in the function.json file and this is fine if all the parameters are present in the query. The problem is, I would like to fetch data based on different parameters and it is possible that not all these parameters will be sent for each query. Is there a way this function API dynamic enough to create the SQL query in run time and fetch the data from Cosmos?

绑定能实现的动态比较有限。如果传入json,则可以在绑定定义中获取传入的json数据的键值(这在某种意义上被认为是动态的)。不过还是推荐使用cosmosdb SDK来实现动态化。

Instead of using the input binding, I tried using the Cosmos python SDK but was getting the below error. "No module named 'azure.cosmos'".

When I normally run a python program to access cosmos outside functions, it is working fine which tells me that I have the necessary libraries already imported. But this is failing when calling from python functions. I've already checked that I'm pointing to the correct interpreter (python 3.8).

我可以重现,这是你的错误(我也可以在使用普通 python 脚本时毫无问题地导入):

我认为问题出在您 运行 在虚拟环境中并且您已经激活了它。

所以,有两种方式:

不要激活虚拟环境,使用命令'func host start'启动你的功能(这将启动全局环境。)。

或者像这样将 'azure.cosmos' 添加到 requirements.txt 文件:

azure-functions
azure.cosmos

以上可以解决您目前遇到的错误

谢谢,

我将 2 个要求添加到我的 requirements.txt 中并得到以下错误。 关于如何修复“AttributeError:模块 'azure.functions' 没有属性 'In'”错误的任何建议?

{[2021-02-10T06:34:16.248Z] Worker failed to function id 4af477f8-eff0-4937-b87f-98f7828d95ec.
[2021-02-10T06:34:16.250Z] Result: Failure
Exception: AttributeError: module 'azure.functions' has no attribute 'In'
Stack:   File "C:\Program Files\Microsoft\Azure Functions Core Tools\workers\python.8/WINDOWS/X64\azure_functions_worker\dispatcher.py", line 271, in _handle__function_load_request
    func = loader.load_function(
  File "C:\Program Files\Microsoft\Azure Functions Core Tools\workers\python.8/WINDOWS/X64\azure_functions_worker\utils\wrappers.py", line 32, in call
    return func(*args, **kwargs)
  File "C:\Program Files\Microsoft\Azure Functions Core Tools\workers\python.8/WINDOWS/X64\azure_functions_worker\loader.py", line 76, in load_function
    mod = importlib.import_module(fullmodname)
  File "C:\Users\dell\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 783, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "D:\Visual Studio\Projects\Functions1\SBTopicTrigger1\__init__.py", line 5, in <module>
    def main(message: func.ServiceBusMessage, inputdocument: func.In[func.Document], outputSbMsg:func.ServiceBusMessage):
.}