簡體   English   中英

使用 Python 3.7 在類中正確使用異步和可等待對象

[英]Correct usage of async and awaitable objects inside class with Python 3.7

我試圖用方法編寫類來調用可等待的對象,但不知道如何正確地做到這一點。 下面的代碼有點工作,但從下面的警告中看出似乎不正確。

class SmartThings():

    async def print_devices(self):
        async with aiohttp.ClientSession() as session:
            api = pysmartthings.SmartThings(session, TOKEN)    
            devices = await api.devices()
            print(devices[0].name)

    def run(self):
        asyncio.run(self.print_devices())

所以我創建了實例並調用了方法:

x = SmartThings()
x.print_devices()
x.run()

..which 工作(打印所需的輸出)但給了我一個RuntimeWarning (可能在調用x.print_devices()

RuntimeWarning: coroutine 'SmartThings.print_devices' was never awaited
  x.print_devices()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

差不多一年前的問題,但我已經以此為起點,我想分享結果。 如果您正在尋找一個工作示例作為開始,這里是:

import aiohttp
import asyncio
import pysmartthings

# Token: https://account.smartthings.com/tokens
TOKEN = 'e54fde2b-f759-4234-b413-WHATEVER'

def main():

    st = SmartThings(TOKEN)
    devices = st.print_devices()
    
    for device in devices :
        print(device.name)


class SmartThings:
    def __init__(self, TOKEN):
        self.TOKEN = TOKEN

    # return devices
    async def search_devices(self):
        async with aiohttp.ClientSession() as session:
            api = pysmartthings.SmartThings(session, self.TOKEN)
            devices = await api.devices()
            return devices

    def print_devices(self):
        loop = asyncio.get_event_loop()
        devices = loop.run_until_complete(self.search_devices())
        loop.close()
    
        return devices

if __name__ == '__main__':
    main()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM