`

python async 使用过程中可变参数,主线程,子线程问题

阅读更多

     1.here is no current event loop in thread 'Thread-1'

 

First, you're getting AssertionError: There is no current event loop in thread 'Thread-1'. because asyncio requires each thread in your program to have its own event loop, but it will only automatically create an event loop for you in the main thread. So if you call asyncio.get_event_loop once in the main thread it will automatically create a loop object and set it as the default for you, but if you call it again in a child thread, you'll get that error. Instead, you need to explicitly create/set the event loop when the thread starts:

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

Once you've done that, you should be able to use get_event_loop() in that specific thread.

It is possible to start an asyncio event loop in a subprocess started via multiprocessing:

import asyncio
from multiprocessing importProcess@asyncio.coroutine
def coro():print("hi")def worker():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(coro())if __name__ =="__main__":
    p =Process(target=worker)
    p.start()
    p.join()

2.  TypeError: insert_data() takes 1 positional argument but 2 were given

    class HandlerAsync():
    async def insert_data(self, **kwargs):
        try:
            data = kwargs.get('kwargs')
            data1 = {"item": data.get('item'),
"event": data.get('event'),
"operator": data.get('operator'),
"timestamp": time.strftime("%Y%m%d%H%M%S")
                    }
            Log.objects.create(**data1)
        except Exception as e:
            print(e)

    async def handler(self, data):
        data = {"item": data.get('item'),
"event": data.get('event'),
"operator": data.get('operator'),
"timestamp": time.strftime("%Y%m%d%H%M%S")
                }
        await self.insert_data(data)

    def execute(self, data):
        try:
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            loop.run_until_complete(self.handler(data))
            loop.close()
        except Exception as e:
            print(traceback.print_exc())

但是换一种参数写法,又正常
class HandlerAsync():

    async def insert_data(self, data):
        try:
            log_data = {"item": data.get('item'),
"event": data.get('event'),
"operator": data.get('operator'),
"timestamp": time.strftime("%Y%m%d%H%M%S")
                    }
            Log.objects.create(**log_data)
        except Exception as e:
            print(e)

    async def handler(self, data):
        await self.insert_data(data)

    def execute(self, data):
        try:
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            loop.run_until_complete(self.handler(data))
            loop.close()
        except Exception as e:
            print(traceback.print_exc())


0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics