我對我的函數應用「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中文網其他相關文章!

Python和C 各有優勢,選擇應基於項目需求。 1)Python適合快速開發和數據處理,因其簡潔語法和動態類型。 2)C 適用於高性能和系統編程,因其靜態類型和手動內存管理。

選擇Python還是C 取決於項目需求:1)如果需要快速開發、數據處理和原型設計,選擇Python;2)如果需要高性能、低延遲和接近硬件的控制,選擇C 。

通過每天投入2小時的Python學習,可以有效提升編程技能。 1.學習新知識:閱讀文檔或觀看教程。 2.實踐:編寫代碼和完成練習。 3.複習:鞏固所學內容。 4.項目實踐:應用所學於實際項目中。這樣的結構化學習計劃能幫助你係統掌握Python並實現職業目標。

在兩小時內高效學習Python的方法包括:1.回顧基礎知識,確保熟悉Python的安裝和基本語法;2.理解Python的核心概念,如變量、列表、函數等;3.通過使用示例掌握基本和高級用法;4.學習常見錯誤與調試技巧;5.應用性能優化與最佳實踐,如使用列表推導式和遵循PEP8風格指南。

Python適合初學者和數據科學,C 適用於系統編程和遊戲開發。 1.Python簡潔易用,適用於數據科學和Web開發。 2.C 提供高性能和控制力,適用於遊戲開發和系統編程。選擇應基於項目需求和個人興趣。

Python更適合數據科學和快速開發,C 更適合高性能和系統編程。 1.Python語法簡潔,易於學習,適用於數據處理和科學計算。 2.C 語法複雜,但性能優越,常用於遊戲開發和系統編程。

每天投入兩小時學習Python是可行的。 1.學習新知識:用一小時學習新概念,如列表和字典。 2.實踐和練習:用一小時進行編程練習,如編寫小程序。通過合理規劃和堅持不懈,你可以在短時間內掌握Python的核心概念。

Python更易學且易用,C 則更強大但複雜。 1.Python語法簡潔,適合初學者,動態類型和自動內存管理使其易用,但可能導致運行時錯誤。 2.C 提供低級控制和高級特性,適合高性能應用,但學習門檻高,需手動管理內存和類型安全。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SublimeText3漢化版
中文版,非常好用

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),