我正在尝试实现这一点,一旦print_handle(data)中的条件满足,我想暂停当前的异步,用我的query2创建一个新的异步请求,关闭该请求,然后继续第一个请求。
from python_graphql_client import GraphqlClient
import asyncio
import os
import requests
headers={'Authorization': "2bTxxxxxxxxxxxxxxxxxxx"}
def print_handle(data):
print(data["data"]["liveMeasurement"]["timestamp"]+" "+str(data["data"]["liveMeasurement"]["power"]))
tall = (data["data"]["liveMeasurement"]["power"])
if tall > 100:
print("OK")
#pause the current async thread, create a new one with the
#query2, close that one, and continue with the first.
client = GraphqlClient(endpoint="wss://api.tibber.com/v1-beta/gql/subscriptions")
query = """
subscription{
liveMeasurement(homeId:"xxxxxxxxxxxxxxxa"){
timestamp
power
}
}
"""
query2 = """
mutation{
sendPushNotification(input: {
title: "Varsel! Høy belastning",
message: "Du bruker nå høyere effekt enn 5 kw, pass på forbruket",
screenToOpen: CONSUMPTION
}){
successful
pushedToNumberOfDevices
}
}
"""
async def main():
await client.subscribe(query=query, headers={'Authorization': "2xxxxxxxxxxxxxxxx"}, handle=print_handle)
asyncio.run(main())发布于 2021-11-16 18:57:24
我认为你混淆了多线程和异步编程。你不想暂停你的线程,因为这意味着你会暂停你的整个程序。我从您的代码中了解到,您希望在满足某些依赖于您的数据的条件时发送推送消息。我不认为你需要为此暂停任何事情。它可以像调度发送该消息的任务一样简单。你可以这样做:
from python_graphql_client import GraphqlClient
import asyncio
import os
import requests
headers={'Authorization': "2bTxxxxxxxxxxxxxxxxxxx"}
def print_handle(data):
print(data["data"]["liveMeasurement"]["timestamp"]+" "+str(data["data"]["liveMeasurement"]["power"]))
tall = (data["data"]["liveMeasurement"]["power"])
if tall > 100:
print("OK")
# schedule async task from sync code
asyncio.create_task(send_push_notification(data))
client = GraphqlClient(endpoint="wss://api.tibber.com/v1-beta/gql/subscriptions")
query = """
subscription{
liveMeasurement(homeId:"xxxxxxxxxxxxxxxa"){
timestamp
power
}
}
"""
query2 = """
mutation{
sendPushNotification(input: {
title: "Varsel! Høy belastning",
message: "Du bruker nå høyere effekt enn 5 kw, pass på forbruket",
screenToOpen: CONSUMPTION
}){
successful
pushedToNumberOfDevices
}
}
"""
async def send_push_notification(data):
#maybe update your query with the received data here
await client.execute_async(query=query2) #pass whatever other params you need
async def main():
await client.subscribe(query=query, headers={'Authorization': "2xxxxxxxxxxxxxxxx"}, handle=print_handle)
asyncio.run(main())https://stackoverflow.com/questions/69990999
复制相似问题