搜索
首页后端开发Python教程cosmosdb 的计时器触发器无法正常工作

cosmosdb 的计时器触发器无法正常工作

问题内容

我对我的函数应用“timertrigger”有疑问。

我开发了此功能来与 telegram 机器人进行通信,以便在 api 请求后发送消息。

我在本地尝试过该功能应用程序,效果很好。但是,当我尝试使用 cosmosdb 存储信息时,遇到问题并且无法保存信息。

我已经设置了将我的应用程序与 telegram 和 cosmosdb 连接所需的所有变量和内容

try:
        database_obj  = client.get_database_client(database_name)
        await database_obj.read()
        return database_obj
    except exceptions.cosmosresourcenotfounderror:
        print("creating database")
        return await client.create_database(database_name)
# </create_database_if_not_exists>
    
# create a container
# using a good partition key improves the performance of database operations.
# <create_container_if_not_exists>
async def get_or_create_container(database_obj, container_name):
    try:        
        todo_items_container = database_obj.get_container_client(container_name)
        await todo_items_container.read()   
        return todo_items_container
    except exceptions.cosmosresourcenotfounderror:
        print("creating container with lastname as partition key")
        return await database_obj.create_container(
            id=container_name,
            partition_key=partitionkey(path="/lastname"),
            offer_throughput=400)
    except exceptions.cosmoshttpresponseerror:
        raise
# </create_container_if_not_exists>

async def populate_container_items(container_obj, items_to_create):
    # add items to the container
    family_items_to_create = items_to_create
    # <create_item>
    for family_item in family_items_to_create:
        inserted_item = await container_obj.create_item(body=family_item)
        print("inserted item for %s family. item id: %s" %(inserted_item['lastname'], inserted_item['id']))
    # </create_item>
# </method_populate_container_items>

async def read_items(container_obj, items_to_read):
    # read items (key value lookups by partition key and id, aka point reads)
    # <read_item>
    for family in items_to_read:
        item_response = await container_obj.read_item(item=family['id'], partition_key=family['lastname'])
        request_charge = container_obj.client_connection.last_response_headers['x-ms-request-charge']
        print('read item with id {0}. operation consumed {1} request units'.format(item_response['id'], (request_charge)))
    # </read_item>
# </method_read_items>

# <method_query_items>
async def query_items(container_obj, query_text):
    # enable_cross_partition_query should be set to true as the container is partitioned
    # in this case, we do have to await the asynchronous iterator object since logic
    # within the query_items() method makes network calls to verify the partition key
    # definition in the container
    # <query_items>
    query_items_response = container_obj.query_items(
        query=query_text,
        enable_cross_partition_query=true
    )
    request_charge = container_obj.client_connection.last_response_headers['x-ms-request-charge']
    items = [item async for item in query_items_response]
    print('query returned {0} items. operation consumed {1} request units'.format(len(items), request_charge))
    # </query_items>
# </method_query_items>

async def run_sample():
    print('aaaa')
    print('sss {0}'.format(cosmosclient(endpoint,credential=key)))
    async with cosmosclient(endpoint, credential = key) as client:
        print('connected to db')
        try:
            database_obj = await get_or_create_db(client, database_name)
            # create a container
            container_obj = await get_or_create_container(database_obj, container_name)
            family_items_to_create = ["link", "ss", "s", "s"]
            await populate_container_items(container_obj, family_items_to_create)
            await read_items(container_obj, family_items_to_create)
            # query these items using the sql query syntax. 
            # specifying the partition key value in the query allows cosmos db to retrieve data only from the relevant partitions, which improves performance
            query = "select * from c "
            await query_items(container_obj, query)   
        except exceptions.cosmoshttpresponseerror as e:
            print('\nrun_sample has caught an error. {0}'.format(e.message))
        finally:
            print("\nquickstart complete")

async def main(mytimer: func.timerrequest) -> none:
    utc_timestamp = datetime.datetime.utcnow().replace(
        tzinfo=datetime.timezone.utc).isoformat()
    
    asyncio.create_task(run_sample())
    logging.info(' sono partito')
    sendnews()
    if mytimer.past_due:
        logging.info('the timer is past due!')

    logging.info('python timer trigger function ran at %s', utc_timestamp)

我已经开始我的功能

func host start --port 7072

但我认为与数据库的连接出了问题,因为 console.log('connected to db') 没有被打印。

似乎所有与cosmosdb相关的操作都没有执行,如果有错误不知道如何解决。

我的终端中没有任何错误,但正如我所说,cosmosdb 似乎不起作用。

我不确定是否向您提供了所有必要的信息。感谢您的帮助。


正确答案


我在使用异步函数时也遇到了同样的问题。当我使用非异步函数时,它对我有用。

参考请查看此 document

我的代码: timetrigger1/__init__.py

import datetime
import logging
import asyncio
import azure.functions as func
from azure.cosmos import cosmos_client
import azure.cosmos.exceptions as exceptions
from azure.cosmos.partition_key import partitionkey

endpoint = "https://timercosmosdb.documents.azure.com/"
key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
database_name = "todolist"
container_name = "test"

def get_or_create_db(client,database_name):
    try:
        database_obj  = client.get_database_client(database_name)
        database_obj.read()
        return database_obj
    except exceptions.cosmosresourcenotfounderror:
        logging.info("creating database")
        return client.create_database_if_not_exists(database_name)
    

def get_or_create_container(database_obj, container_name):
    try:        
        todo_items_container = database_obj.get_container_client(container_name)
        todo_items_container.read()   
        return todo_items_container
    except exceptions.cosmosresourcenotfounderror:
        logging.info("creating container with lastname as partition key")
        return database_obj.create_container_if_not_exists(
            id=container_name,
            partition_key=partitionkey(path="/id"),
            offer_throughput=400)
    except exceptions.cosmoshttpresponseerror:
        raise


def populate_container_items(container_obj,items):
    inserted_item = container_obj.create_item(body=items)
    logging.info("inserted item for %s family. item id: %s" %(inserted_item['lastname'], inserted_item['id']))

def read_items(container_obj,id):
        item_response = container_obj.read_item(item=id, partition_key=id)
        request_charge = container_obj.client_connection.last_response_headers['x-ms-request-charge']
        logging.info('read item with id {0}. operation consumed {1} request units'.format(item_response['id'], (request_charge)))

def query_items(container_obj, query_text):
    query_items_response = container_obj.query_items(
        query=query_text,
        enable_cross_partition_query=true
    )
    request_charge = container_obj.client_connection.last_response_headers['x-ms-request-charge']
    items = [item for item in query_items_response]
    logging.info('query returned {0} items. operation consumed {1} request units'.format(len(items), request_charge))

def run_sample():
    logging.info('aaaa')
    client = cosmos_client.cosmosclient(endpoint, key)
    logging.info('connected to db')
    try:
        id= "test"
        database_obj = get_or_create_db(client,database_name)

        container_obj = get_or_create_container(database_obj,container_name)
        item_dict = {
                "id": id,
                "lastname": "shandilya",
                "firstname": "vivek",
                "gender": "male",
                "age": 35
            }
        populate_container_items(container_obj,item_dict)
        read_items(container_obj,id)

        query = "select * from c "
        query_items(container_obj, query)   
    except exceptions.cosmoshttpresponseerror as e:
        logging.info('\nrun_sample has caught an error. {0}'.format(e.message))
    finally:
        logging.info("\nquickstart complete")

def main(mytimer: func.timerrequest) -> none:
    utc_timestamp = datetime.datetime.utcnow().replace(
        tzinfo=datetime.timezone.utc).isoformat()
    
    run_sample()
    logging.info(' sono partito')
    logging.info('python timer trigger function ran at %s', utc_timestamp)

output

functions:

        timertrigger1: timertrigger

for detailed output, run func with --verbose flag.
[2024-01-30t09:00:24.818z] executing 'functions.timertrigger1' (reason='timer fired at 2024-01-30t14:30:24.7842979+05:30', id=5499e180-4964-4d7e-b9f2-b024860945dd)
[2024-01-30t09:00:24.822z] trigger details: unscheduledinvocationreason: ispastdue, originalschedule: 2024-01-30t14:30:00.0000000+05:30
[2024-01-30t09:00:25.022z] aaaa
[2024-01-30t09:00:26.387z] connected to db
[2024-01-30t09:00:28.212z] inserted item for shandilya family. item id: test
[2024-01-30t09:00:28.373z] read item with id test. operation consumed 1 request units
[2024-01-30t09:00:28.546z]
quickstart complete
[2024-01-30t09:00:28.548z] python timer trigger function ran at 2024-01-30t09:00:25.008468+00:00
[2024-01-30t09:00:28.547z]  sono partito
[2024-01-30t09:00:28.546z] query returned 1 items. operation consumed 1 request units
[2024-01-30t09:00:28.592z] executed 'functions.timertrigger1' (succeeded, id=5499e180-4964-4d7e-b9f2-b024860945dd, duration=3793ms)
[2024-01-30t09:00:29.296z] host lock lease acquired by instance id '000000000000000000000000aae5f384'.

{
    "id": "test",
    "lastName": "Shandilya",
    "firstName": "Vivek",
    "gender": "male",
    "age": 35,
    "_rid": "ey58AO9yWqwCAAAAAAAAAA==",
    "_self": "dbs/ey58AA==/colls/ey58AO9yWqw=/docs/ey58AO9yWqwCAAAAAAAAAA==/",
    "_etag": "\"01001327-0000-1a00-0000-65b8baac0000\"",
    "_attachments": "attachments/",
    "_ts": 1706605228
}

以上是cosmosdb 的计时器触发器无法正常工作的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:stackoverflow。如有侵权,请联系admin@php.cn删除
Python与C:学习曲线和易用性Python与C:学习曲线和易用性Apr 19, 2025 am 12:20 AM

Python更易学且易用,C 则更强大但复杂。1.Python语法简洁,适合初学者,动态类型和自动内存管理使其易用,但可能导致运行时错误。2.C 提供低级控制和高级特性,适合高性能应用,但学习门槛高,需手动管理内存和类型安全。

Python vs. C:内存管理和控制Python vs. C:内存管理和控制Apr 19, 2025 am 12:17 AM

Python和C 在内存管理和控制方面的差异显着。 1.Python使用自动内存管理,基于引用计数和垃圾回收,简化了程序员的工作。 2.C 则要求手动管理内存,提供更多控制权但增加了复杂性和出错风险。选择哪种语言应基于项目需求和团队技术栈。

科学计算的Python:详细的外观科学计算的Python:详细的外观Apr 19, 2025 am 12:15 AM

Python在科学计算中的应用包括数据分析、机器学习、数值模拟和可视化。1.Numpy提供高效的多维数组和数学函数。2.SciPy扩展Numpy功能,提供优化和线性代数工具。3.Pandas用于数据处理和分析。4.Matplotlib用于生成各种图表和可视化结果。

Python和C:找到合适的工具Python和C:找到合适的工具Apr 19, 2025 am 12:04 AM

选择Python还是C 取决于项目需求:1)Python适合快速开发、数据科学和脚本编写,因其简洁语法和丰富库;2)C 适用于需要高性能和底层控制的场景,如系统编程和游戏开发,因其编译型和手动内存管理。

数据科学和机器学习的Python数据科学和机器学习的PythonApr 19, 2025 am 12:02 AM

Python在数据科学和机器学习中的应用广泛,主要依赖于其简洁性和强大的库生态系统。1)Pandas用于数据处理和分析,2)Numpy提供高效的数值计算,3)Scikit-learn用于机器学习模型构建和优化,这些库让Python成为数据科学和机器学习的理想工具。

学习Python:2小时的每日学习是否足够?学习Python:2小时的每日学习是否足够?Apr 18, 2025 am 12:22 AM

每天学习Python两个小时是否足够?这取决于你的目标和学习方法。1)制定清晰的学习计划,2)选择合适的学习资源和方法,3)动手实践和复习巩固,可以在这段时间内逐步掌握Python的基本知识和高级功能。

Web开发的Python:关键应用程序Web开发的Python:关键应用程序Apr 18, 2025 am 12:20 AM

Python在Web开发中的关键应用包括使用Django和Flask框架、API开发、数据分析与可视化、机器学习与AI、以及性能优化。1.Django和Flask框架:Django适合快速开发复杂应用,Flask适用于小型或高度自定义项目。2.API开发:使用Flask或DjangoRESTFramework构建RESTfulAPI。3.数据分析与可视化:利用Python处理数据并通过Web界面展示。4.机器学习与AI:Python用于构建智能Web应用。5.性能优化:通过异步编程、缓存和代码优

Python vs.C:探索性能和效率Python vs.C:探索性能和效率Apr 18, 2025 am 12:20 AM

Python在开发效率上优于C ,但C 在执行性能上更高。1.Python的简洁语法和丰富库提高开发效率。2.C 的编译型特性和硬件控制提升执行性能。选择时需根据项目需求权衡开发速度与执行效率。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热工具

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境