Use Asyncio inside Blender API to consume external API

Hello everyone, I hope you are all OK,

I started a project where I want to consume an authentication api from a window made with the blender api.

But I’m having the following points:
1- how can i made an async function inside that class ?
2- there is some material or documentarion about this topic ?

class UploadModelPanel(bpy.types.Panel):
    bl_label = "Blendon"
    bl_idname = "blendon.panel"
    bl_space_type = "VIEW_3D"
    bl_region_type = "UI"
    bl_category = "Blendon Tools"

    def draw(self, context):
        layout = self.layout

        row = layout.row()
        row.operator("window.login", text="Authentication")



class Login_Window(bpy.types.Operator):
    bl_label = "Login Window"
    bl_idname = "window.login"
    
    key : bpy.props.StringProperty(name="Product Key", default="teste")
    token : bpy.props.StringProperty(name="Token")

    async def do_post(self):
            async with session.get(url) as response:
                  data = await response.text()
                  self.token = data.message


    async def make_account(self):
        url = "https://dog.ceo/api/breeds/image/random"
        async with aiohttp.ClientSession() as session:
            post_tasks = []
            post_tasks.append(do_post(session, url))
            await asyncio.gather(*post_tasks)

    def execute(self, context):
        return {'FINISHED'} 

    def invoke(self, context, event):
        make_account(self)
        return context.window_manager.invoke_props_dialog(self)

    

def register():
    bpy.utils.register_class(UploadModelPanel) 
    bpy.utils.register_class(Login_Window) 

def unregister():
    bpy.utils.unregister_class(UploadModelPanel)
    bpy.utils.unregister_class(Login_Window)

if __name__ == "__main__":
    register()

I wish Blender would offer its event loop in an asyncio-compatible form. This would make it easier to install Python tasks that run concurrently with the UI, without having to use modal operators.

One thing that would need to be added to the GHOST layer in order for this to work is the ability to monitor file descriptors with select/poll.

1 Like