在python中使用asyncio实现异步行为

A lot has changed since I last published my post on handling long-running async tasks in Python using celery. Last time we used it to run a few async tasks to fetch data from some service which took around 1–5 minutes.

自从我上次发表关于使用celery处理Python中长时间运行的异步任务的文章以来,发生了很多变化。 上一次,我们使用它运行一些异步任务来从某些服务中获取数据,这大约需要1-5分钟

Although I will still use celery for these types of long-running tasks, there is a subset of tasks that are better handled inside the execution thread itself. Today we will discuss a way of handling such operations.

尽管我仍将芹菜用于这些类型的长时间运行的任务,但仍有一部分任务可以在执行线程内部更好地处理。 今天,我们将讨论处理此类操作的方法。

To the people who know me, I switched to a new role which allowed me to write Node.js over a year ago and I have been working on it since then. During my time working and building APIs using it, I have started falling for the way in which Node handles Async behavior and long-running tasks.

对于认识我的人来说,我转用了一个新角色,该角色使我一年多以前就可以编写Node.js,并且从那时起我一直在努力。 在使用它工作和构建API的过程中,我开始迷恋Node处理异步行为和长时间运行的任务的方式

The idea is simple, if the task is waiting for some IO, we can run some other task in the mean-time. Only the part that needs it, will wait for it.

这个想法很简单,如果任务正在等待一些IO,我们可以同时运行其他任务。 只有需要它的部分才会等待。

I wanted to use the same concept in Python.

我想在Python中使用相同的概念。

Fortunately, in the Python version 3.4, they have introduced asyncio for the same purpose. In this post, we are going to talk a little about it and try to understand its importance.

幸运的是,在Python版本3.4 ,他们出于相同的目的引入了asyncio 。 在这篇文章中,我们将讨论一下它,并试图理解它的重要性。

By the end of the post, you will be able to understand the importance of async functions and will be able to start using them into your codebase.

在本文的结尾,您将能够理解异步函数的重要性,并将能够开始在代码库中使用它们。

先决条件 (Prerequisite)

I am using Python 3.8 for this tutorial and you might want to use the same to run and try out examples. You can try them online as well.

我在本教程中使用的是Python 3.8 ,您可能希望使用相同的代码来运行并试用示例。 您也可以在线尝试它们。

Python中的基本异步功能 (Basic async function in Python)

This is how we write a basic async function in Python.

这就是我们用Python编写基本异步函数的方式。

import asyncioasync def func1(a):
print(f"started func 1: {a + 1}")
await asyncio.sleep(1)
return a + 1asyncio.run(func1(1))

Response

响应

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值