Три способа выполнить множество задач с asyncio
Функция для примера:
async def do_it(n):
await asyncio.sleep(random.uniform(0.5, 1))
return n
1. Последовательный вызов
async def main():
for i in range(100):
result = await do_it(i)
Такой вызов имеет смысл только тогда, когда результат одной задачи требуется для вызова следующей.
Если они независимы, то это антипаттерн, так как аналогичен простому синхронному вызову по очереди.
2. Упорядоченный результат
async def main():
tasks = [do_it(i) for i in range(100)]
results = await asyncio.gather(*tasks)
Выполняет корутины конкурентно и возвращает результат в виде списка.
Полезен когда требуется получить результаты в том же порядке в котором задачи отправлены.
3. Результат по мере готовности
tasks = [asyncio.create_task(do_it(i)) for i in range(100)]
for cor in asyncio.as_completed(tasks):
result = await cor
Так же выполняет корутины конкурентно, но не гарантирует порядок. Результат возвращается по мере готовности, каждый отдельно.
Полезен когда нужно обработать любой ответ как можно скорее.
#async
Caramelized Onion Pasta
Ingredients:
Oven:
*300 g shallots
*300 g vegan cream cheese
*60 ml maple syrup
*200 g smoked tofu
*salt and pepper
*Oil as desired
Aside from that:
*350g pasta
*200 g dried tomatoes
*1 bunch of fresh wild garlic
*60 ml pasta water
#paste
@dishes
Rice Noodle Spring Salad
Ingredients:
*1 carrot
*100 g fresh red cabbage
*1/2 cucumber
*1/2 red onion
*1 mango
*250 g rice noodles
Peanut sauce:
*2 cm ginger
*2 cloves of garlic
*200 g peanut butter
*20 ml sesame oil
*50 ml maple syrup
*50 ml soy sauce
*150ml water
Toppings:
Chili flakes
Coriander, mint
peanuts
#paste
@dishes
You Need To Taste This Green Goddess Salad With Watermelon & Pasta
Ingredients:
*200 grams of watermelon
*100 grams of cucumber
*200 grams of pasta
Dressing:
*80 grams of spinach
*1/2 bunch basil
*1 clove of garlic
*1/2 onion
*50 grams of peas
*40ml oil
*25ml water
*1 tbsp vinegar
*1 tsp salt
*40 grams of walnuts
*juice of a lemon
*1 tbsp yeast flakes
*pinch of pepper
toppings:
Walnuts, Basil, Chili Flakes
#paste
@dishes
Pasta Alla Vodka with Pancetta🧀
Ingredients:
*350g. Rigatoni pasta (Can be replaced with penne pasta)
*2 Tbsp Olive oil
*150g. diced Pancetta
*2 Shallot onion, finely chopped
*3 Garlic cloves, finely chopped
*1/2 Tsp Red-Chilli flakes
*1/2 Tsp dried Oregano
*1/2 cup Vodka
*1 cup Tomato sauce
*1/4 cup Tomato paste with basil pesto
*2 cup Heavy cream
*1/4 cup Parmesan cheese, plus more for serving
*1 tablespoon roughly chopped fresh Basil
*2 tablespoons roughly chopped Italian Parsley
#paste
@dishes
ROASTED RED PEPPER PASTA! 🌶️
Ingredients:
* 400 g. Giant Fusilli Pasta
* 4 Red Bell Peppers
* 2 Shallot onion
* 1 head Garlic
* Olive oil
* 1 cup Heavy Cream
* Red chili flakes
* Italian herbs
* 1 tbsp Tomato paste
* 1 tbsp Butter
* Salt/Pepper
#paste
@dishes