#3 转载:Python 异步编程与数据库

2020-11-22

这是大神 zzzeek 2015 年发表的一篇文章,详细介绍了关于 SQLAlchemy 与异步编程的一些事情。解答了我关于如何实现异步编程的一些疑惑。
我曾反复阅读这篇文章好多遍,以求能够更加准确地领会到大佬阐述的意思。我认为每个 Python 的使用者都应该阅读阅读。

#1 RuntimeError: Event loop is closed

2019-02-11

开发过程中发现报错:

Traceback (most recent call last):
  ...
  File "/usr/local/python3.7.3/lib/python3.7/asyncio/streams.py", line 353, in close
    return self._transport.close()
  File "/usr/local/python3.7.3/lib/python3.7/asyncio/selector_events.py", line 690, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "/usr/local/python3.7.3/lib/python3.7/asyncio/base_events.py", line 719, in call_soon
    self._check_closed()
  File "/usr/local/python3.7.3/lib/python3.7/asyncio/base_events.py", line 508, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed

经过检查,发现是我在代码中调用了 asyncio.run(协程方法(*args, **kwargs))
总是有些同步代码中需要调用协程方法,没有办法。

改成这样就可以了:

asyncio.get_event_loop().run_until_complete(协程方法(*args, **kwargs))

如果是在线程中就改成:

asyncio.new_event_loop().run_until_complete(协程方法(*args, **kwargs))

否则会报:RuntimeError: There is no current event loop in thread 'Thread-2'.

线程中 run_sync

RuntimeError: This event loop is already running

attached to a different loop

Traceback (most recent call last):
  File "/opt/fuckTheWorld/core/framework.py", line 194, in fuck
    value = asyncio.new_event_loop().run_until_complete(lego.get(key))
  File "/usr/local/python3.7.3/lib/python3.7/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "/opt/fuckTheWorld/core/lego.py", line 30, in execute
    data = await super().execute(*args, **options)
  File "/opt/fuckTheWorld/lego/client.py", line 476, in execute
    return await conn.retry.call_with_retry(
  File "/opt/fuckTheWorld/lego/retry.py", line 51, in call_with_retry
    return await do()
  File "/opt/fuckTheWorld/lego/client.py", line 455, in _send_command_parse_response
    return await self.parse_response(conn, command_name, **options)
  File "/opt/fuckTheWorld/lego/client.py", line 494, in parse_response
    response = await connection.read_response()
  File "/opt/fuckTheWorld/lego/connection.py", line 934, in read_response
    await self.disconnect()
  File "/opt/fuckTheWorld/lego/connection.py", line 822, in disconnect
    await self._writer.wait_closed()  # type: ignore[union-attr]
  File "/usr/local/python3.7.3/lib/python3.7/asyncio/streams.py", line 359, in wait_closed
    await self._protocol._get_close_waiter(self)
RuntimeError: Task <Task pending name='Task-45' coro=<Fuck.execute() running at /opt/fuckTheWorld/core/lego.py:30> cb=[_run_until_complete_cb() at /usr/local/python3.7.3/lib/python3.7/asyncio/base_events.py:184]> got Future <Future pending> attached to a different loop