Issue
I'm trying to achieve that once the condition is met in print_handle(data)
I want to pause the current async, create a new async request with my query2
, close that request, then continue with the first one.
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())
Solution
I think you are confusing multithreading and asynchronous programming. You do not want to pause your thread because that would mean you would pause your whole program. I take from your code that you want to send a push message once some condition depending on your data is met. I don‘t think you need to pause anything for that. It can be as simple as scheduling a task for sending that message. You could go with something like this:
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())
Answered By - thisisalsomypassword
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.