zeyneloz / onesignal_sdk

A Python wrapper around the OneSignal API

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

AsyncClient not working

Prince-Jonathan opened this issue · comments

Great job by the way! I have managed to send notifications with the Client instance. I however cannot get the AsyncClient instance to work when called within a route's method.
An extract of my script:

from onesignal_sdk.client import AsyncClient 

@app.route('/api/notify')
async def notify():
        client = AsyncClient(app_id=MY_APP_ID, rest_api_key=MY_REST_API_KEY)
	notification_body = {
	    'contents': {'tr': 'Yeni bildirim', 'en': 'New notification'},
            'included_segments': ['Subscribed Users'],
	    'headings': {'en': 'Title of Message'},
	}
	response = await client.send_notification(notification_body)
	print(response.body)
	return {'success':'true'}

What am I missing? Do I need to employ asyncio?

Hey @Prince-Jonathan. Thanks!
Which part is not working exactly? Do you get an exception or the notification is not being sent? Can you also post the result of the print statement in the script you executed.

Alright, I get this prompt when I try to access the endpoint from my browser: TypeError: The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a coroutine. I'm not sure it gets to print the response.

Well this error is not related to onesignal_sdk. I am not sure which web framework you are using but apparently it does not directly support asyncio, so you cant use async def... with @app.route. You need to run your program in a async event loop. I would suggest you to go with a web framework that supports ASGI. Check out quart for example. Or find how to use asyncio with existing one.

Very well, I really needed clarity on that. I will try it out.

I have tried first: restructuring my script to using Quart to purport Flask. It was a bit undue, with regard to the current complexity of my code. I have however resolved working with asyncio and its working just fine. I have my code extract looking like:

import asyncio
from onesignal_sdk.client import AsyncClient 

async def create_note():
    client = AsyncClient(app_id=MY_APP_ID, rest_api_key=MY_REST_API_KEY)
    notification_body = {
			'contents': {'tr': 'Yeni bildirim', 'en': 'New notification'},
			'included_segments': ['Subscribed Users'],
			"headings": {"en": "Title of Message"},
	}
    response = await client.send_notification(notification_body)
    return response.body

loop = asyncio.get_event_loop()

@app.route('/api/notify')
def notify():
	return loop.run_until_complete(create_note())

You have been consistent with timely response. Thanks!