1. run_in_executer
import asyncio
import time
def sync_send_email():
time.sleep(2)
return "Done"
async def send_email():
loop = asyncio.get_event_loop()
result = await loop.run_in_executor(None, sync_send_email) # 扔进线程池执行
print(result)
asyncio.run(send_email())
2. 用asyncio.to_thread同步转异步‘
若是已经写好了同步发送邮件,则可以通过asyncio.to_thread同步转为异步发送
import asyncio
import time
def send_email():
time.sleep(2)
return "Done"
async def async_send_email():
result = await asyncio.to_thread(send_email) # 一行搞定!
print(result)
asyncio.run(async_send_email())
3. 通过httpx异步发送邮件
异步直接实现发送邮件可以通过httpx实现,如下
async def async_send_email():
async with httpx.AsyncClient(verify=False) as client:
response = await client.post(
f"https://{settings.domain}/email",
json=data,
cookies=cookies,
)
4. 用信号量控制并发
# 用信号量(asyncio.Semaphore)控制并发
async def run_with_limit(task_func, max_cnotallow=50):
semaphore = asyncio.Semaphore(max_concurrency)
async def wrapper():
async with semaphore:
return await asyncio.to_thread(task_func)
return wrapper
async def send_batch_email():
tasks = [run_with_limit(send_one_email)() for _ in range(1000)]
await asyncio.gather(*tasks)
asyncio.run(send_batch_email())
-
5. thread
thread = threading.Thread(func, *args)
thread.join()