RuntimeError: There is no current event loop in thread 'Dummy-1'

*爱你&永不变心* 提交于 2020-01-14 14:47:51

问题


I am working on a web application with the backend in Python and a Django server. I have a few raspberry pis which are sending data to a server and then I am supposed to get those data from my backend. I succeeded in doing it out of my project so I am pretty sure about the code. Now I wanna integrate this function to my project so here is the file :

loop = asyncio.get_event_loop()

class StartApp:
    def __init__(self, interval=1):
            self.interval = interval
            Mqtt = multiprocessing.Process(target = self.runMqtt)
            loop.run_until_complete(runCoap())
    async def runCoap():
            print('COUCOU C cOAP')
            protocol = await Context.create_client_context()

            requestTemp = Message(code=GET, uri='coap://129.6.60.38/other/sensors/temperature')
            requestHumidity = Message(code=GET, uri='coap://129.6.60.38/other/sensors/humidity')
            while True:
                time.sleep(1)
                try:
                    responseTemp = await protocol.request(requestTemp).response
                    responseHumidity = await protocol.request(requestHumidity).response
                except Exception as e:
                    print('Failed to fetch resource:')
                    print(e)
                else:
                    print('Result: %s\n%r'%(responseTemp.code, responseTemp.payload))
                    print('Result: %s\n%r'%(responseHumidity.code, responseHumidity.payload))

and I get this error when running my app :

Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f55cdc989d8>
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/django/utils/autoreload.py", line 228, in wrapper
    fn(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/runserver.py", line 147, in inner_run
    handler = self.get_handler(*args, **options)
  File "/usr/local/lib/python3.5/dist-packages/django/contrib/staticfiles/management/commands/runserver.py", line 28, in get_handler
    handler = super(Command, self).get_handler(*args, **options)
  File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/runserver.py", line 68, in get_handler
    return get_internal_wsgi_application()
  File "/usr/local/lib/python3.5/dist-packages/django/core/servers/basehttp.py", line 47, in get_internal_wsgi_application
    return import_string(app_path)
  File "/usr/local/lib/python3.5/dist-packages/django/utils/module_loading.py", line 20, in import_string
    module = import_module(module_path)
  File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 665, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "/home/vincentnahmias/Workspace/IOT-Testbed-Dashboard/IOT-Testbed-Dashboard/wsgi.py", line 13, in <module>
    from Dashboard.pySharkToDb.LAN_to_DB import StartApp
  File "/home/vincentnahmias/Workspace/IOT-Testbed-Dashboard/Dashboard/pySharkToDb/LAN_to_DB.py", line 17, in <module>
    loop = asyncio.get_event_loop()
  File "/usr/lib/python3.5/asyncio/events.py", line 632, in get_event_loop
    return get_event_loop_policy().get_event_loop()
  File "/usr/lib/python3.5/asyncio/events.py", line 578, in get_event_loop
    % threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'Dummy-1'.

I tried to print the loop but it seems no loop is created so I assume there is a conflict between Django and asyncio because I am able to run this very same function out of the project using:

if __name__ == "__main__":
    asyncio.get_event_loop().run_until_complete(main())

where main is the name of the method I named runCoap.


回答1:


So thanks to @user4815162342 here is the solution :

def __init__(self, interval=1):
        self.interval = interval
        logging.basicConfig(level=logging.INFO)
        loop = asyncio.new_event_loop();
        asyncio.set_event_loop(loop)
        loop.run_until_complete(self.runCoap())
        loop.close()
        Mqtt = multiprocessing.Process(target = self.runMqtt)
async def runCoap(self):
        print('COUCOU C cOAP')
        protocol = await Context.create_client_context()

        requestTemp = Message(code=GET, uri='coap://129.6.60.38/other/sensors/temperature')
        requestHumidity = Message(code=GET, uri='coap://129.6.60.38/other/sensors/humidity')
        while True:
            await asyncio.sleep(1)
            try:
                responseTemp = await protocol.request(requestTemp).response
                responseHumidity = await protocol.request(requestHumidity).response
            except Exception as e:
                print('Failed to fetch resource:')
                print(e)
            else:
                print('Result: %s\n%r'%(responseTemp.code, responseTemp.payload))
                print('Result: %s\n%r'%(responseHumidity.code, responseHumidity.payload))


来源:https://stackoverflow.com/questions/50935153/runtimeerror-there-is-no-current-event-loop-in-thread-dummy-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!