我有一个异步功能,需要每隔N分钟使用apscheduller运行一次.下面有一个python代码
URL_LIST = ['<url1>',
'<url2>',
'<url2>',
]
def demo_async(urls):
"""Fetch list of web pages asynchronously."""
loop = asyncio.get_event_loop() # event loop
future = asyncio.ensure_future(fetch_all(urls)) # tasks to do
loop.run_until_complete(future) # loop until done
async def fetch_all(urls):
tasks = [] # dictionary of start times for each url
async with ClientSession() as session:
for url in urls:
task = asyncio.ensure_future(fetch(url, session))
tasks.append(task) # create list of tasks
_ = await asyncio.gather(*tasks) # gather task responses
async def fetch(url, session):
"""Fetch a …Run Code Online (Sandbox Code Playgroud) 我在Python 3.5+中读过许多关于asyncio/ async/的博客文章,问题/答案await,很多都是复杂的,我发现最简单的可能是这个.它仍然使用ensure_future,并且为了学习Python中的异步编程,我想看看是否有更简单的例子是可能的(即,执行基本异步/等待示例所需的最小工具是什么).
问题:为了学习Python中的异步编程,是否可以通过仅使用这两个关键字+ + +其他Python代码但没有其他函数来提供一个显示如何async/ await工作的简单示例?asyncio.get_event_loop()run_until_completeasyncio
示例:类似这样的事情:
import asyncio
async def async_foo():
print("async_foo started")
await asyncio.sleep(5)
print("async_foo done")
async def main():
asyncio.ensure_future(async_foo()) # fire and forget async_foo()
print('Do some actions 1')
await asyncio.sleep(5)
print('Do some actions 2')
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Run Code Online (Sandbox Code Playgroud)
但没有ensure_future,仍然演示了await/async的工作原理.
我见过使用运行阻塞代码
loop = asyncio.get_running_loop()
await loop.run_in_executor(None, blockingfunc)
Run Code Online (Sandbox Code Playgroud)
和
loop = asyncio.get_event_loop()
await loop.run_in_executor(None, blockingfunc)
Run Code Online (Sandbox Code Playgroud)
我们什么时候应该使用asyncio.get_running_loop()vs asyncio.get_event_loop()?
我以前做过 Lambda 函数,但没有在 Python 中做过。我知道在 Javascript 中 Lambda 支持异步处理函数,但是如果我在 Python 中尝试它,我会得到一个错误。
这是我要测试的代码:
async def handler(event, context):
print(str(event))
return {
'message' : 'OK'
}
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误:
An error occurred during JSON serialization of response: <coroutine object handler at 0x7f63a2d20308> is not JSON serializable
Traceback (most recent call last):
File "/var/lang/lib/python3.6/json/__init__.py", line 238, in dumps
**kw).encode(obj)
File "/var/lang/lib/python3.6/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/var/lang/lib/python3.6/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/var/runtime/awslambda/bootstrap.py", line 149, in decimal_serializer
raise TypeError(repr(o) …Run Code Online (Sandbox Code Playgroud) python amazon-web-services async-await aws-lambda python-3.6
python ×4
async-await ×2
python-3.x ×2
aiohttp ×1
apscheduler ×1
asynchronous ×1
aws-lambda ×1
python-3.6 ×1