celery

安装 安装celery包 选一个broker,这里我选rabbitmq 选一个backend,这里我选redis python环境下需要安装redis包 插件 flower可以实时监控celery状态 配置 1 2 3 poetry add celery docker run -d -p 5672:5672 rabbitmq docker run -d -p 6379:6379 redis 配置文件celeryconfig.py: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 broker_url = 'pyamqp://guest:guest@localhost' result_backend = 'rpc://' task_serializer = 'json' result_serializer = 'json' accept_content = ['json'] timezone = 'Europe/Oslo' enable_utc = True task_routes = { 'task....

created: 2020-02-26  |  updated: 2020-02-26  |  阿秀

python asyncio

使用async关键字的原生协程 异步生成器(在async def中使用yield),例如: 1 2 async def async_gen(): yield 1 协程函数(即协程),例如: 1 2 3 async def cor(): res = await awaitable() return res 其中awaitable()指的是实现了__await__()协议的对象 协程的一个例子 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import asyncio async def cor_1(n): return list(range(n)) async def cor_2(n): return list(range(n)) async def chain(m, n): r1 = await cor_1(m) r2 = await cor_2(n) print(r1, r2) async def main(): await asyncio....

created: 2020-02-10  |  updated: 2020-02-10  |  阿秀

Python 基于生成器的协程

从生成器到协程 python的协程是从yield和yield from发展而来的,因为yield一开始是用来实现生成器的,为了使得协程不是某种生成器,在python 3.5开始提出使用新关键字async和await来实现了原生协程。 基于生成器的协程 使用yield实现的协程是基于生成器的,将在3.10弃用。建议没接触过python协程的直接接触async声明的原生协程 一个简单的协程例子 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 def cor(init): index = init while True: recv = yield f'now at index {index}' print(f'recv: {recv}') index += 1 c = cor(init=0) c.send(None) r1 = c.send('1') print(r1) r2 = c.send('2') print(r2) send()是实现协程的一个核心点 协程的参数用于协程开始之前进行相关初始化操作。 协程中表达式recv = yield result, 其中result是协程的返回值(没有result时表示没有返回值),而recv是用来接收外部传入到协程中的数据 一个注意的点是,程序的运行顺序是先接收数据,再返回值,即index+=1后再返回给r1 使用装饰器预激活协程 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 from functools import wraps def decorator(coroutine): @wraps(coroutine) def func(*args, **kwargs): primed_cor = coroutine(*args, **kwargs) primed_cor....

created: 2018-03-10  |  updated: 2018-03-10  |  阿秀

Python 位置参数,关键字参数, 默认参数, 可变长位置参数,可变长关键字参数

假设这里有一简单的函数 1 2 def printf(first, second, third): print(first, second) 位置参数 位置参数指的是调用函数时,参数顺序相一致 1 2 printf(1, 2, 3) print(4, 5, 6) 关键字参数 关键字参数指使用键值对key=value这样的方式调用程序 1 printf(first=1, second=2, third=3) 需要注意的是,当你使用关键字参数这种传递方式后,该函数后续参数将不能使用位置参数这一形式进行传递,如: 1 2 printf(first=1, 2, 3) # 错误 printf(1, second=2, third=3) # 正确 即保证位置参数必须放在关键字参数前。类似的,若函数中含默认参数,则后续参数也必须为含默认参数的参数 1 2 3 4 5 def func(first, second=2, third): # 错误 pass def func(first, second=2, third=3): # 正确 pass 除此之外,关键字参数的顺序可以打乱(位置参数顺序不可以改变):...

created: 2017-10-10  |  updated: 2017-10-10  |  阿秀