0

0

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

WBOY

WBOY

发布时间:2024-02-22 12:40:11

|

1193人浏览过

|

来源于stackoverflow

转载

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 a container
# using a good partition key improves the performance of database operations.
# 
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
# 

async def populate_container_items(container_obj, items_to_create):
    # add items to the container
    family_items_to_create = items_to_create
    # 
    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']))
    # 
# 

async def read_items(container_obj, items_to_read):
    # read items (key value lookups by partition key and id, aka point reads)
    # 
    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)))
    # 
# 

# 
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_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))
    # 
# 

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 似乎不起作用。

SUN2008 企业网站管理系统2.0 beta
SUN2008 企业网站管理系统2.0 beta

1、数据调用该功能使界面与程序分离实施变得更加容易,美工无需任何编程基础即可完成数据调用操作。2、交互设计该功能可以方便的为栏目提供个性化性息功能及交互功能,为产品栏目添加产品颜色尺寸等属性或简单的留言和订单功能无需另外开发模块。3、静态生成触发式静态生成。4、友好URL设置网页路径变得更加友好5、多语言设计1)UTF8国际编码; 2)理论上可以承担一个任意多语言的网站版本。6、缓存机制减轻服务器

下载

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


正确答案


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

参考请查看此 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
}

相关标签:

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
console接口是干嘛的
console接口是干嘛的

console接口是一种用于在计算机命令行或浏览器开发工具中输出信息的工具,提供了一种简单的方式来记录和查看应用程序的输出结果和调试信息。本专题为大家提供console接口相关的各种文章、以及下载和课程。

410

2023.08.08

console.log是什么
console.log是什么

console.log 是 javascript 函数,用于在浏览器控制台中输出信息,便于调试和故障排除。想了解更多console.log的相关内容,可以阅读本专题下面的文章。

478

2024.05.29

数据库三范式
数据库三范式

数据库三范式是一种设计规范,用于规范化关系型数据库中的数据结构,它通过消除冗余数据、提高数据库性能和数据一致性,提供了一种有效的数据库设计方法。本专题提供数据库三范式相关的文章、下载和课程。

333

2023.06.29

如何删除数据库
如何删除数据库

删除数据库是指在MySQL中完全移除一个数据库及其所包含的所有数据和结构,作用包括:1、释放存储空间;2、确保数据的安全性;3、提高数据库的整体性能,加速查询和操作的执行速度。尽管删除数据库具有一些好处,但在执行任何删除操作之前,务必谨慎操作,并备份重要的数据。删除数据库将永久性地删除所有相关数据和结构,无法回滚。

2068

2023.08.14

vb怎么连接数据库
vb怎么连接数据库

在VB中,连接数据库通常使用ADO(ActiveX 数据对象)或 DAO(Data Access Objects)这两个技术来实现:1、引入ADO库;2、创建ADO连接对象;3、配置连接字符串;4、打开连接;5、执行SQL语句;6、处理查询结果;7、关闭连接即可。

346

2023.08.31

MySQL恢复数据库
MySQL恢复数据库

MySQL恢复数据库的方法有使用物理备份恢复、使用逻辑备份恢复、使用二进制日志恢复和使用数据库复制进行恢复等。本专题为大家提供MySQL数据库相关的文章、下载、课程内容,供大家免费下载体验。

251

2023.09.05

vb中怎么连接access数据库
vb中怎么连接access数据库

vb中连接access数据库的步骤包括引用必要的命名空间、创建连接字符串、创建连接对象、打开连接、执行SQL语句和关闭连接。本专题为大家提供连接access数据库相关的文章、下载、课程内容,供大家免费下载体验。

319

2023.10.09

数据库对象名无效怎么解决
数据库对象名无效怎么解决

数据库对象名无效解决办法:1、检查使用的对象名是否正确,确保没有拼写错误;2、检查数据库中是否已存在具有相同名称的对象,如果是,请更改对象名为一个不同的名称,然后重新创建;3、确保在连接数据库时使用了正确的用户名、密码和数据库名称;4、尝试重启数据库服务,然后再次尝试创建或使用对象;5、尝试更新驱动程序,然后再次尝试创建或使用对象。

402

2023.10.16

php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

74

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号